0

我有两个结果集,看起来大致如下:

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 中执行此操作(如果可能,使用联合)?我当前的 SQL,希望这能更好地解释我想要做什么:

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

2 回答 2

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
于 2012-11-13T12:36:28.327 回答
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 小提琴演示

于 2012-11-13T12:17:28.337 回答