[英]SQL query to group transactions by month
----------------------------------------
|transaction_id|customer_id|month|value|
----------------------------------------
我正在尋找一個 SQL 查詢,該查詢將返回在 10 月份而不是 11 月份進行更多交易的客戶的客戶 ID,或者僅在 11 月份進行交易(而在 10 月份沒有交易)的客戶的客戶 ID。 月份列是字符串類型(不是日期)
我在想一個內部連接可以做到,但過去我不知道如何解決這個問題。
這是我嘗試的
select customer_id
from tbl_name
where (select count(month is 'October') > count(month is 'November') from tbl_name)
謝謝
你計算記錄。 所以你聚合。 您想要每個 customer_id 的計數。 所以你要按customer_id分組。 您在查詢中忘記了這一點。
然后您將比較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;
如您所見,您不需要兩次訪問該表。 只需匯總,看看你有什么:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.