考虑以下数据:
+-----+--------+----------+-------+ | 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 | +-----+--------+----------+-------+
我想查询此表格以生成显示以下内容的报告:
最近连续三个月中color =“black”的refs列表 - 基于样本数据,这将返回113.
编辑,我不得不简化原来的问题。
答案 0 :(得分:1)
您有两个部分 - 过去三个月的数据转换和过滤。可能最简单的方法是聚合然后使用having
:
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;