SQL 查询 - 仅计算满足特定条件的月份



我在编写 sql 查询时遇到问题...基本上我有大约一百万行(卡(,交易分为几列 - 月(12 个月(。

因此,每一行都显示该卡每月的交易规模。 现在的问题是 - 我试图只选择一年中仅 7 个月满足特定条件的卡。

条件是每个月(持续时间7个月(他们花费超过5 000欧元。

我只是不知道有什么功能可以向我显示 7 个月的 resulst..我已经写了整个查询,但一整年,现在我需要将其缩小到 7 个月,但不知道如何......我已经"谷歌"到处都是。 重要提示 - 7 个月不需要连续 - 它可以是一年中的任何一个月。 有人可以帮助我吗?

坦克你,K。

您应该将数据模型修复为将月份存储在行中,而不是列中。

这是一个解决方案,它在子查询中使用union all来动态生成这样的结构,然后使用having子句进行聚合和过滤:

select card
from (
select card, month_1 spent from mytable
union all select card, month_2 from mytable
-- ... one "union all" statement per column ...
union all select card, month_12 from mytable
) t
group by card
having sum(case when spent > 5000 then 1 end) = 7

这假设数据结构如下:

card      -- primary key
month_1   -- amount spent during the 1stmonth
month_2   -- amount spent during the 2nd month
...
month_2   -- amount spent during the 12th month

最新更新