2017-02-14 65 views
1

我有以下查詢:轉換行的列標題與合計

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 

但我沒有彙總。

有沒有一種方法可以做到這一點?

+1

嘗試查找_pivot與count_,大量[網站上的示例](http://stackoverflow.com/search?q=%5Bsql-server%5D+pivot+with+count)。 – Tanner

+0

如果可能,請嘗試將所有內容都作爲文本發佈。在您的案例中(預期和實際結果)。也嘗試包括示例DDL,DML語句 – TheGameiswar

+0

感謝@Tanner,設法弄清楚並更新了我的文章。我無法弄清楚如何獲得總數。 – Philip

回答

1

試試這個..

SELECT *, 
(select sum(v) 
from 
(values(male), 
     (female), 
     (transgender), 
     (unknown)) 
     as val(v)) as total 
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 

對於更新的要求:
我建議把整個表成readabilty一些臨時表,做這個

所以你上面的查詢會是這樣的

SELECT *, 
(select sum(v) 
from 
(values(male), 
     (female), 
     (transgender), 
     (unknown)) 
     as val(v)) as total 
into #temp 
from 
rest of pivot query 

然後再做分組總計

select 
case when grouping(agegroup)=1 then 'total' else agegroup end agegroup, 
sum(male) as male, 
sum(female) as 'female', 
sum(trans) as 'trans', 
sum(unknown) as 'unknown', 
sum(total) as 'Total' 
from #temp 
group by 
grouping sets 
(
(agegroup), 
() 
) 
+0

謝謝。儘管給出了這個錯誤:消息8158,級別16,狀態1,行135 「val」的列數多於列列表中指定的列數。 – Philip

+0

Val應該是這樣的.values(男),(女)..我會更新一次我接近一臺電腦。可能在接下來的1小時 – TheGameiswar

+0

謝謝@TheGameiswar – Philip