先放上寫好的 Demo
好久沒來問問題~有個SQL語法需求~有兩張表內容如下
表B
表F
表F的BId對應表B的Id,做join後如下
select * from B
inner join F on B.Id = F.BId
需求來了,我想要在同一列,顯示一間公司的每年狀態+某年某季的Count,不知道有什麼方法可以更好處理這種問題! 我自己有硬兜出以下語法,是可以呈現我要的結果,但我知道很爛且效能很差,應該需要新的知識補充加強,感謝各位
我的語法如下:
;with T1 as
(
select B.*,F.Season,F.Count from B
inner join F on B.Id = F.BId
)
select distinct
Name,
(select top 1 Status from T1 as T2 where T1.Name = T2.Name and Year=109 ) as [109_Status],
(select top 1 Status from T1 as T2 where T1.Name = T2.Name and Year=110 ) as [110_Status],
(select top 1 Count from T1 as T2 where T1.Name = T2.Name and Year=109 and Season=1 ) as [109_s1_count],
(select top 1 Count from T1 as T2 where T1.Name = T2.Name and Year=109 and Season=2 ) as [109_s2_count],
(select top 1 Count from T1 as T2 where T1.Name = T2.Name and Year=109 and Season=3 ) as [109_s3_count],
(select top 1 Count from T1 as T2 where T1.Name = T2.Name and Year=110 and Season=1 ) as [110_s1_count],
(select top 1 Count from T1 as T2 where T1.Name = T2.Name and Year=110 and Season=2 ) as [110_s2_count],
(select top 1 Count from T1 as T2 where T1.Name = T2.Name and Year=110 and Season=3 ) as [110_s3_count]
from T1
我想要呈現的結果如下:
你可以嘗試使用 MAX
with GROUP BY
;with T1 as
(
select B.*,F.Season,F.Count from B
inner join F on B.Id = F.BId
)
SELECT Name,
MAX(CASE WHEN Year = 109 THEN Status END),
MAX(CASE WHEN Year = 110 THEN Status END),
MAX(CASE WHEN Year = 109 AND Season = 1 THEN [COUNT] END),
MAX(CASE WHEN Year = 109 AND Season = 2 THEN [COUNT] END),
MAX(CASE WHEN Year = 109 AND Season = 3 THEN [COUNT] END),
MAX(CASE WHEN Year = 110 AND Season = 1 THEN [COUNT] END),
MAX(CASE WHEN Year = 110 AND Season = 2 THEN [COUNT] END),
MAX(CASE WHEN Year = 110 AND Season = 3 THEN [COUNT] END)
FROM T1
GROUP BY Name