【求sql语句】两表间有重复数据,求两表总数(去掉重复)。 PS:guid相同代表两条数据相同,该怎么处理
【求sql语句】两表间有重复数据,求两表总数(去掉重复)。 PS:guid相同代表两条数据相同
order表
come表
情况是这样的,两表中有一部分数据时相同的(guid相同就代表两条数据是相同的)。
去掉重复之后两表的总数应该是9条(既aaaa...、zzzz...、bbbb...、cccc...、dddd...、eeee...、ffff...、xxxx...、yyyy...)。
我想要的功能是以Time和projectid进行分组,求出Order表总数、Come表总数、两表之和总数
我最终想看到的效果如下:
------解决方案--------------------
order表
- HTML code
GUID projectid Time aaaa... 项目A组 2012-2-1 zzzz... 项目A组 2012-2-1 bbbb... 项目A组 2012-2-2 cccc.. 项目B组 2012-2-2 dddd.. 项目C组 2012-2-3 eeee... 项目B组 2012-2-1
come表
- HTML code
GUID projectid Time aaaa... 项目A组 2012-2-1 bbbb... 项目A组 2012-2-2 eeee... 项目B组 2012-2-1 ffff... 项目W组 2012-2-5 xxxx... 项目A组 2012-2-1 yyyy... 项目A组 2012-2-1
情况是这样的,两表中有一部分数据时相同的(guid相同就代表两条数据是相同的)。
去掉重复之后两表的总数应该是9条(既aaaa...、zzzz...、bbbb...、cccc...、dddd...、eeee...、ffff...、xxxx...、yyyy...)。
我想要的功能是以Time和projectid进行分组,求出Order表总数、Come表总数、两表之和总数
我最终想看到的效果如下:
- HTML code
Time projectid Order表总数 Come表总数 两表之和总数(去重) 2012-2-1 项目A组 2 3 4 2012-2-1 项目B组 1 1 1 2012-2-2 项目A组 1 1 1 2012-2-2 项目B组 1 0 1 2012-2-3 项目C组 1 0 1 2012-2-5 项目W组 0 1 1
------解决方案--------------------
- SQL code
select Time,projectid, Order表总数=sum(case when type='Order' then 1 else 0 end), Come表总数=sum(case when type='Come' then 1 else 0 end), 两表之和总数=count(distinct GUID) from (select *,type='Order' from [Order] union all select *,type='Come' from Come) t group by Time,projectid
------解决方案--------------------
- SQL code
select Time,projectid,count(o.*) as Order表总数,count(c.*) as Come表总数 ,count(v.*) as 两表之和总数(去重) from order as o, Come as c,(select * from order as o unionselect * from Come as c) as v group by Time,projectid
------解决方案--------------------
- SQL code
--> 测试数据: @order表 declare @order表 table (GUID varchar(4),projectid varchar(7),Time datetime) insert into @order表 select 'aaaa','项目A组','2012-2-1' union all select 'zzzz','项目A组','2012-2-1' union all select 'bbbb','项目A组','2012-2-2' union all select 'cccc','项目B组','2012-2-2' union all select 'dddd','项目C组','2012-2-3' union all select 'eeee','项目B组','2012-2-1' --> 测试数据: @come表 declare @come表 table (GUID varchar(4),projectid varchar(7),Time datetime) insert into @come表 select 'aaaa','项目A组','2012-2-1' union all select 'bbbb','项目A组','2012-2-2' union all select 'eeee','项目B组','2012-2-1' union all select 'ffff','项目W组','2012-2-5' union all select 'xxxx','项目A组','2012-2-1' union all select 'yyyy','项目A组','2012-2-1' select Time=convert(varchar(10),Time,120),projectid, [Order表总数]=sum(case when c=1 then 1 else 0 end), [Come表总数]=sum(case when c=2 then 1 else 0 end), [总数]=count(distinct GUID) from(select *,1 as c from @order表 union all select *,2 from @come表) a group by Time,projectid /* Time projectid Order表总数 Come表总数 总数 ---------- --------- ----------- ----------- ----------- 2012-02-01 项目A组 2 3 4 2012-02-01 项目B组 1 1 1 2012-02-02 项目A组 1 1 1 2012-02-02 项目B组 1 0 1 2012-02-03 项目C组 1 0 1 2012-02-05 项目W组 0 1 1 */