简体   繁体   English

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

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

I am having a trouble writing a sql query...basically I have about a million or so rows (cards) with transactions divided into columns - months (12 months).我在编写 sql 查询时遇到了麻烦...基本上我有大约一百万行(卡片)的事务分为列 - 月(12 个月)。

So each row shows how big transaction did the card do each month.因此,每一行都显示该卡每月进行的交易量。 Now the problem is - I am trying to select only the cards who have met a certain condition only 7 months during the year.现在的问题是 - 我试图只选择一年中只有 7 个月满足特定条件的卡。

The condition is each month (duration 7 months) they spend more then 5 000 eur.条件是每个月(持续 7 个月)他们花费超过 5 000 欧元。

I just do not know what is the function that would show me the resulst for the 7 months..I have wrote the whole query but for the whole year, now I need to narrow it down just to the 7 months, but do not know how...I have "googled" all over.我只是不知道是什么功能可以显示 7 个月的结果……我已经写了整个查询,但是整年,现在我需要将其缩小到 7 个月,但不知道如何......我已经“谷歌”了。 Important - the 7 months doesnt need to be in a row - it can be any month during the year.重要 - 7 个月不需要连续 - 可以是一年中的任何月份。 Could anybody help me with this?有人可以帮我解决这个问题吗?

Tank you, K.坦克你,K。

You should fix your data model to store months in rows, not in columns.您应该修复数据模型以将月份存储在行中,而不是列中。

Here is a solution that uses union all in a subquery to generate such a structure on the fly, then aggregates and filters with a having clause:这是一个解决方案,它在子查询中使用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

This assumes a data structure like:这假设数据结构如下:

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