如何在 SQL 中查询 table 以生成列名根据条件垂直堆叠的结果?

How do I query a table in SQL to produce a result where column names are stacked vertically based on a condition?

假设我有一个 SQL table 标题为 Users 的示例数据如下:

Description          Days
--------------------------
Healthy               10
High-blood pressure   20          
Cholesterol           23 
Diabetes              31
High-blood pressure   8
Healthy               12
Diabetes              18              
Cholesterol           25
High-blood pressure   20
Healthy               6

我如何生成如下所示的结果,其中列:Less_than_20_days、20_days 和 Greater_than_20_days 包含上面 table 的计数

Description         Less_than_20_days         20_days         Greater_than_20_days
-----------------------------------------------------------------------------------
Healthy                    3                     0                     0
High-blood pressure        1                     2                     0
Cholesterol                0                     0                     2
Diabetes                   1                     0                     1

我试图让它在 SQL 服务器中工作,并尝试使用联合运算符、temp tables 和 ctes,但我似乎无法获得所需的结果。

如有任何帮助,我们将不胜感激!

您可以将 casesum() 结合使用:

select
     [Description]
    ,sum(case when [Days] < 20 then 1 else 0 end) as Less_than_20_days
    ,sum(case when [Days] = 20 then 1 else 0 end) as d20_days
    ,sum(case when [Days] > 20 then 1 else 0 end) as Greater_than_20_days
from users
group by [Description]

使用条件聚合:

select description,
       sum(case when days < 20 then 1 else 0 end) as num_lt_20,
       sum(case when days = 20 then 1 else 0 end) as num_eq_20,
       sum(case when days > 20 then 1 else 0 end) as num_gt_20
from t
group by description