对列案例

时间:2016-10-08 01:50:31

标签: sql

我想创建一个计算年龄天数的SQL脚本,以及类似的东西:(我得到的是将一列逐个值分解为三列的天数值)这是我的输出创建

Days0To30  Days30to60  Daysto60to90
----------------------------------
50$      | 10$        | 90$
60$      | 0          | 10$
0        | 0          | 5$
0        | 10$        | 0
10$      | 0          | 0
0$       | 0          | 0
1240     | 0          | 0

我想创建一个计算年龄天数的SQL脚本,例如:

------------------------------------------
Days0To30       | 4           
Days30to60      | 2           
Daysto60to90    | 3

2 个答案:

答案 0 :(得分:0)

您可以使用conditional aggregation

select count(case when Days0To30 <> 0 then 1 end) as Days0To30,
       count(case when Days30to60 <> 0 then 1 end) as Days30to60,
       count(case when Daysto60to90 <> 0 then 1 end) as Daysto60to90
from yourtable

答案 1 :(得分:0)

SELECT SUM(CASE WHEN Days0To30 > 0 THEN 1 ELSE 0 END) as Days0To30 ,
       SUM(CASE WHEN Days30to60 > 0 THEN 1 ELSE 0 END) as Days30to60,
       SUM(CASE WHEN Daysto60to90 > 0 THEN 1 ELSE 0 END) as Daysto60to90
FROM   SOME_TABLE