我可能已经阅读了十几个类似的主题,但我无法使用它们来解决我的问题。我很接近,可能距离解决方案只有一两步。
我有一个表,我加载的数据看起来与此类似:
CustName | Model | Serial | Color | MonthlyCount
Freds | 123AB | L23456 | BLUE | 987
Freds | 123AB | L23456 | GREEN | 1127
Jimmys | 111SS | L11234 | BLUE | 2245
Erikas | 123AB | L11331 | RED | 12
Erikas | 123AB | L11331 | BLUE | 10
Erikas | 123AB | L11331 | GREEN | 19
我想要的是将它们组合成一行:
CustName | Model | Serial | GreenCount | BlueCount | RedCount
Freds | 123AB | L23456 | 987 | 1127 |
Jimmys | 111SS | L11234 | | 2245 |
Erikas | 123AB | L11331 | 19 | 10 | 12
序列号是唯一的,所以我尝试使用T1.Serial = T2.Serial和T1.Serial = T3.Serial进行内部连接T1到T2和T1到T3但是我仍然得到带有NULLS的行,示例Erikas返回5行,其中只有一行包含所有数据
我尝试使用Where" T1.MonthlyCount"(etc)IS NOT NULL但是没有过滤任何行:
Select T1.CustName
,T1.Model
,T1.Serial
,(Select T1.MonthlyCount Where T1.Color = 'BLUE') As BlueCount
,(Select T2.MonthlyCount Where T2.Color = 'GREEN') As GreenCount
,(Select T3.MonthlyCount Where T3.Color = 'RED') As RedCount
From Table1 T1
Inner Join Table2 T2
on T1.Serial = T2.Serial
Inner Join Table3 T3
on T1.Serial = T3.Serial
Where T1.MonthlyCount IS NOT NULL
AND T2.MonthlyCount IS NOT NULL
AND T3.MonthlyCount IS NOT NULL
Group By Serial, CustName, Model, Color, MonthlyCount
我得到的是:
CustName | Model | Serial | GreenCount | BlueCount | RedCount
Freds | 123AB | L23456 | NULL | NULL | NULL
Freds | 123AB | L23456 | 987 | NULL | NULL
Freds | 123AB | L23456 | NULL | 1127 | NULL
Freds | 123AB | L23456 | 987 | 1127 | NULL <--Expected
Jimmys | 111SS | L11234 | NULL | NULL | NULL
Jimmys | 111SS | L11234 | NULL | 2245 | NULL <--Expected
Erikas | 123AB | L11331 | NULL | NULL | NULL
Erikas | 123AB | L11331 | 19 | NULL | NULL
Erikas | 123AB | L11331 | NULL | 10 | NULL
Erikas | 123AB | L11331 | NULL | NULL | 12
Erikas | 123AB | L11331 | 19 | 10 | 12 <--Expected
我只是在寻找标记为预期的上述3行。非常感谢任何帮助。
答案 0 :(得分:4)
使用条件聚合,并且只按您希望在每行中唯一的列进行聚合。而且,你有更多的联接而不是必要的。没有必要。
Select T1.CustName, T1.Model, T1.Serial,
sum(case when T1.Color = 'BLUE' then t1.MonthlyCount else 0 end) As BlueCount,
sum(case when T1.Color = 'GREEN' then t1.MonthlyCount else 0 end) As GreenCount,
sum(case when T1.Color = 'RED' then t1.MonthlyCount else 0 end) As RedCount
From Table1 T1
Group By T1.CustName, T1.Model, T1.Serial;
如果您想要NULL
而不是0
,请从每个条款中删除else 0
。
Here是一个SQL小提琴,证明它有效。
答案 1 :(得分:3)
Select T1.CustName
,T1.Model
,T1.Serial
,SUM(CASE WHEN Color = 'Blue' THEN MonthlyCount ELSE 0 END) BlueCount
,SUM(CASE WHEN Color = 'Green' THEN MonthlyCount ELSE 0 END) GreenCount
,SUM(CASE WHEN Color = 'Red' THEN MonthlyCount ELSE 0 END) RedCount
From Table1 T1
Group By Serial, CustName, Model