我有以下查詢:轉換行的列標題與合計
SELECT
g.Gender,
a.AgeGroup,
count(*) as Count
FROM
client c
INNER JOIN AgeGroup a
ON c.age BETWEEN a.StartRange AND a.EndRange
INNER JOIN Gender G on
C.GenderID = G.GenderID
group by
g.Gender,
a.AgeGroup
order by AgeGroup, Gender
其結果如下:
Gender AgeGroup Count
Male <=25 4
Unknown <=25 2
Female >35 2223
Male >35 6997
Transgender >35 43
Unknown >35 2
Female 26-35 413
Male 26-35 590
Transgender 26-35 5
什麼我需要嘗試做雖然是轉換性別列到列標題幷包括總計。
AgeGroup Male Female Trans Unknown Total
<= 25: 4 0 0 2 6
26 - 35: 590 413 5 0 1008
> 35: 6997 2223 43 2 9265
Total: 7591 2636 48 4 10279
我走了這麼遠:
SELECT *
FROM (
SELECT
g.Gender as [Gender],
a.AgeGroup
FROM
client c
INNER JOIN AgeGroup a
ON c.age BETWEEN a.StartRange AND a.EndRange
INNER JOIN Gender G on
C.GenderID = G.GenderID
) as s
PIVOT
(
COUNT(Gender)
FOR [Gender] IN (Male,Female,Transgender,Unknown)
)AS pvt
返回此:
AgeGroup Male Female Transgender Unknown
<=25 4 0 0 2
26-35 590 413 5 0
>35 6997 2223 43 2
但我沒有彙總。
有沒有一種方法可以做到這一點?
嘗試查找_pivot與count_,大量[網站上的示例](http://stackoverflow.com/search?q=%5Bsql-server%5D+pivot+with+count)。 – Tanner
如果可能,請嘗試將所有內容都作爲文本發佈。在您的案例中(預期和實際結果)。也嘗試包括示例DDL,DML語句 – TheGameiswar
感謝@Tanner,設法弄清楚並更新了我的文章。我無法弄清楚如何獲得總數。 – Philip