SQL联合列数相同,数据类型相同,数据不同

时间:2012-11-13 12:13:23

标签: sql join sql-server-2008-r2 union

我有两个看起来像这样的结果集:

Id       Name    Count
1        Asd     1  
2        Sdf     4    
3        Dfg     567    
4        Fgh     23    

但是第二个的Count列数据不同,我希望两者都显示出来,就像这样:

Id       Name    Count from set 1    Count from set two
1        Asd     1                   15
2        Sdf     4                   840
3        Dfg     567                 81
4        Fgh     23                  9

如何在SQL中执行此操作(如果可能,使用union)? 我目前的SQL,希望这能更好地解释我想做的事情:

(SELECT Id, Name, COUNT(*) FROM Customers where X)
union
(SELECT Id, Name, COUNT(*) FROM Customers where Y)

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

;WITH Unioned
AS
(
    SELECT 'Set1' FromWhat, Id, Name FROM Table1
    UNION ALL
    SELECT 'Set2', Id, Name FROM Table2
)
SELECT 
  Id, 
  Name,
  SUM(CASE FromWhat WHEN 'Set1' THEN 1 ELSE 0 END) 'Count from set 1',
  SUM(CASE FromWhat WHEN 'Set2' THEN 1 ELSE 0 END) 'Count from set 2'
FROM Unioned
GROUP BY Id, Name;

SQL Fiddle Demo

答案 1 :(得分:1)

select * 
from
(
    SELECT 'S1' as dataset, Id, Name, COUNT(*) as resultcount FROM Customers where X
    union
    SELECT 'S2',Id, Name, COUNT(*) FROM Customers where Y
) s
pivot
(sum(resultcount) for dataset in (s1,s2)) p