繁体   English   中英

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

[英]SQL query - counting only the months that met certain condition

我在编写 sql 查询时遇到了麻烦...基本上我有大约一百万行(卡片)的事务分为列 - 月(12 个月)。

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

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

我只是不知道是什么功能可以显示 7 个月的结果……我已经写了整个查询,但是整年,现在我需要将其缩小到 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM