在SQLITE中转置行列和计算每列的实例数

时间:2018-10-26 06:38:33

标签: sql sqlite

我的表格结构为

|creationDate|rule.      |position| 
|01.01.2018  |squid:S1132|12      |
|01.01.2018  |squid:S1132|14      |
|01.01.2018  |squid:S1132|19      |
|01.01.2018  |squid:S1121|12      |
|01.01.2018  |squid:S1121|14      |
|01.02.2018  |squid:S1130|12      |

我的目标是计算每个日期的规则数量,并在不同的列中报告它们。

|creationDate| S1132      | S1121 | S1130 |
|01.01.2018  | 3          |2      | 0     |
|01.02.2018  | 0          |0      | 1     |

我总共有180条规则... 是否可以在单个查询中完成?

运行此查询

select creationDate , count("creationDate") as "squid:S1132" 
from SONAR_ISSUES 
where rule='squid:S1132' group by creationDate

我得到了这个结果

|creationDate|S1132  | 
|01.01.2018  |3      |

我可以对每个规则进行类似的查询,但是,我无法将它们合并...

2 个答案:

答案 0 :(得分:1)

您可以尝试使用条件聚合

DEMO

select 
   creationDate, 
   count(case when rule='squid:S1132' then "creationDate" end) as "squid:S1132",
   count(case when rule='squid:S1121' then "creationDate" end) as "squid:S1121" ,
   count(case when rule='squid:S1130' then "creationDate" end) as "squid:S1130" 
from SONAR_ISSUES 
group by creationDate

答案 1 :(得分:1)

在以下情况下使用大小写进行尝试

select creationDate ,count(case when rule='squid:S1132' then 1 end) as S1132,
count(case when rule='squid:S1121' then 1 end) as S1121,
count(case when rule='squid:S1130' then 1 end) as S1130    
from SONAR_ISSUES 
group by 
creationDate