table1 表结构
id username state
1 u1 1
2 u2 1
3 u1 0
4 u1 1table2 表结构
id username state
1 u1 1
2 u2 1
3 u2 0user 表结构
id name
1 u1
2 u2要生成的结果是
统计表table1中共有多少条state=1 的u1的数据,table2中共有多少条state=1 的u1的数据
统计表table1中共有多少条state=1 的u2的数据,table2中共有多少条state=1 的u2的数据
例如:
user ct1 ct2
u1 2 1
u2 1 1
id username state
1 u1 1
2 u2 1
3 u1 0
4 u1 1table2 表结构
id username state
1 u1 1
2 u2 1
3 u2 0user 表结构
id name
1 u1
2 u2要生成的结果是
统计表table1中共有多少条state=1 的u1的数据,table2中共有多少条state=1 的u1的数据
统计表table1中共有多少条state=1 的u2的数据,table2中共有多少条state=1 的u2的数据
例如:
user ct1 ct2
u1 2 1
u2 1 1
Create table table1(
id int, username nchar(20), state bit)
Create table table2(
id int, username nchar(20), state bit)Create table [user](
id int, name nchar(20))
--测试数据
insert into table1
select '1','u1','1' union all
select '2','u2','1' union all
select '3','u1','0' union all
select '4','u1','1'insert into table2
select '1','u1','1' union all
select '2','u2','1' union all
select '3','u2','0' insert into [user]
select '1','u1' union all
select '2','u2' --楼主你要的结果select t.username as [user],
SUM(case when type=1 then cast(state as int) else 0 end) as ct1,
SUM(case when type=2 then cast(state as int) else 0 end) as ct2
from
(
select *, 1 as type from table1
union
select *, 2 as type from table2
) t
GROUp by t.username
--删除环境
drop table table1
drop table table2
drop table [user]
*****************************************************************************
最近没想出什么好签名!
我用的是ems sql manager数据库管理器执行
select t.username as [user],
... ...
GROUp by t.username
后 提示
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'int) else 0 end) as ct1,
SUM(case when type=2 then cast(state as int) else 0 en' at line 2