简体   繁体   English

按月对事务进行分组的 SQL 查询

[英]SQL query to group transactions by month

----------------------------------------
|transaction_id|customer_id|month|value|
----------------------------------------

I am looking for a SQL query that would return customers ID of the customers that had more transactions in the month of October instead of November or of customers that ONLY had transactions in November (and none in October).我正在寻找一个 SQL 查询,该查询将返回在 10 月份而不是 11 月份进行更多交易的客户的客户 ID,或者仅在 11 月份进行交易(而在 10 月份没有交易)的客户的客户 ID。 The month column is of type string (not a date)月份列是字符串类型(不是日期)

I was thinking an inner join could do it, but past that I do not know how to approach this problem.我在想一个内部连接可以做到,但过去我不知道如何解决这个问题。

This is what I attempted这是我尝试的

select customer_id
from tbl_name
where (select count(month is 'October') > count(month is 'November') from tbl_name)

Thank you谢谢

You count records.你计算记录。 So you aggregate.所以你聚合。 You want counts per customer_id.您想要每个 customer_id 的计数。 So you'd group by customer_id.所以你要按customer_id分组 You forgot this in your query.您在查询中忘记了这一点。

Then you'd compare the counts in the HAVING clause, ie after having counted October and November records.然后您将比较HAVING子句中的计数,即在计算了 10 月和 11 月的记录之后。

select customer_id
from tbl_name
where month in ('October', 'November')
group by customer_id
having count(case when month = 'October' then 1 end) >
       count(case when month = 'November' then 1 end)
    or count(case when month = 'October' then 1 end) = 0;

You don't need to access the table twice as you see.如您所见,您不需要两次访问该表。 Just aggregate and see what you have :-)只需汇总,看看你有什么:-)

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

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