SQL Server - simple way to create pivot

删除回忆录丶 提交于 2019-12-10 12:06:36

问题


Does anybody knows a simple way to create a pivot of this result:

[0-1]  [1-2]  [2-3]  [3-4]
12      45      29    5

This result is created with query:

 SELECT [0-1]   = SUM(CASE WHEN AGE >= 0 AND AGE <= 1 THEN 1 ELSE 0 END),
       [1-2]  = SUM(CASE WHEN AGE > 1 AND AGE <= 2 THEN 1 ELSE 0 END),
       [2-3] = SUM(CASE WHEN AGE > 2 AND AGE <= 3 THEN 1 ELSE 0 END)
    FROM dbo.Persons

I want to show the column values as rows i.e the output should like this:

[0-1]      12
[1-2]      45
[2-3]      29
[3-4]       5

Links to articles/blogs are also welcomed. Please suggest a simple and easy to follow solution.


回答1:


Here is a way that uses cross join and aggregation:

select ages.minage, ages.maxage,
       sum(case when age > ages.minage and age <= ages.maxage then 1 else 0 end) as cnt
from dbo.Persons cross join
     (select -1 as minage, 1 as maxage union all
      select 1, 2 union all
      select 2, 3
     ) as ages
group by ages.minage, ages.maxage

I like this method because it is easy to add new age ranges. Note this also includes the ranges.



来源:https://stackoverflow.com/questions/18355311/sql-server-simple-way-to-create-pivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!