考虑以下数据:
+-----+--------+----------+-------+ |参考文献 |颜色 | 月份 |价值 | +-----+--------+----------+-------+ |112 |红色 |一月 | 16 | |113 |黑色 |一月 | 10 | |113 |黑色 |一月 | 11 | |112 |黄色 |二月 | 10 | |114 |红色 |二月 | 7 | |113 |黑色 |二月 | 10 | |113 |黑色 |二月 | 14 | |112 |黄色 |二月 | 15 | |113 |黑色 |三月 | 8 | |112 |橙色 |三月 | 1 | |114 |蓝色 |四月 | 6 | |113 |黑色 |四月 | 4 | +-----+--------+----------+-------+
我想查询此表以生成显示以下内容的报告:
连续三个月颜色="黑色"的参考文献列表 - 基于样本数据,这将返回113。
编辑,我不得不简化原始问题。
您有两个部分 - 透视数据和筛选过去三个月的数据。 可能最简单的方法是聚合然后使用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;