基于月度数据中特定条件的SQL报表
考虑以下数据: +-----+--------+----------+-------+ | Ref | Colour | Month | Value | +-----+--------+----------+-------+ | 112 | Red | January | 16 | | 113 | Black | January | 10 | | 113 | Black | January | 11 | | 112 | Yellow | February | 10 | | 114 | Red | February | 7 | | 113 | Black | February | 10 | | 113 | Black | February | 14 | | 112 | Yellow | February | 15 | | 113 | Black | March | 8 | | 112 | Orange | March | 1 | | 114 | Blue | April | 6 | | 113 | Black | April | 4 | +-----+--------+----------+-------+ 我想查询此表以生成显示以下内容的报告: 在过去连续三个月内颜色=黑色的参考列表-根据样本数据,返回113基于月度数据中特定条件的SQL报表,sql,oracle,pivot,Sql,Oracle,Pivot,考虑以下数据: +-----+--------+----------+-------+ | Ref | Colour | Month | Value | +-----+--------+----------+-------+ | 112 | Red | January | 16 | | 113 | Black | January | 10 | | 113 | Black | January | 11 | | 112 | Yellow | February
编辑,我不得不简化原来的问题。这有两个部分——数据透视和过滤过去三个月的数据。最简单的方法可能是聚合,然后使用:
你需要中间结果,还是返回透视报告的单个查询?第一部分实际上对我来说更重要。如果他有所有的月份,这个查询会变得很长。我想知道是否还有更简洁的问题。我已经简化了原来的问题,第一部分对我来说更重要。
select ref,
sum(case when month = 'January' then value else 0 end) as Jan,
sum(case when month = 'February' then value else 0 end) as Feb,
sum(case when month = 'March' then value else 0 end) as Mar,
sum(case when month = 'April' then value else 0 end) as Apr
from t
where colour = 'Black'
group by ref
having sum(case when month = 'February' then value else 0 end) > 0 and
sum(case when month = 'March' then value else 0 end) > 0 and
sum(case when month = 'April' then value else 0 end) > 0;