使用总计将行转换为列标题

时间:2017-02-14 11:34:03

标签: sql-server tsql

我有以下查询:

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 个答案:

答案 0 :(得分: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

更新要求:
我建议将整个表放入一些临时表中以获得可读性并执行此操作

所以你的上述查询会像这样

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),
 ()
 )