【求sql语句】两表间有重复数据,求两表总数(去掉重复)。 PS:guid相同代表两条数据相同
order表
GUID projectid Time aaaa... 项目A组 2012-2-1zzzz... 项目A组 2012-2-1bbbb... 项目A组 2012-2-2cccc.. 项目B组 2012-2-2dddd.. 项目C组 2012-2-3eeee... 项目B组 2012-2-1
GUID projectid Time aaaa... 项目A组 2012-2-1bbbb... 项目A组 2012-2-2eeee... 项目B组 2012-2-1ffff... 项目W组 2012-2-5xxxx... 项目A组 2012-2-1yyyy... 项目A组 2012-2-1
Time projectid Order表总数 Come表总数 两表之和总数(去重)2012-2-1 项目A组 2 3 42012-2-1 项目B组 1 1 12012-2-2 项目A组 1 1 12012-2-2 项目B组 1 0 12012-2-3 项目C组 1 0 12012-2-5 项目W组 0 1 1
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) tgroup by Time,projectid
[解决办法]
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 vgroup by Time,projectid
[解决办法]
--> 测试数据: @order表declare @order表 table (GUID varchar(4),projectid varchar(7),Time datetime)insert into @order表select 'aaaa','项目A组','2012-2-1' union allselect 'zzzz','项目A组','2012-2-1' union allselect 'bbbb','项目A组','2012-2-2' union allselect 'cccc','项目B组','2012-2-2' union allselect 'dddd','项目C组','2012-2-3' union allselect '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 allselect 'bbbb','项目A组','2012-2-2' union allselect 'eeee','项目B组','2012-2-1' union allselect 'ffff','项目W组','2012-2-5' union allselect 'xxxx','项目A组','2012-2-1' union allselect '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 42012-02-01 项目B组 1 1 12012-02-02 项目A组 1 1 12012-02-02 项目B组 1 0 12012-02-03 项目C组 1 0 12012-02-05 项目W组 0 1 1*/