我有2个表:表1(用户)包含用户/领导者的姓名,表2(交易)包含用户交易记录,其列名为“原因”
有几个“原因”可以分为两类。
User Table
--------------
User Leader
--------------
user1 Leader1
user2 Leader1
user3 Leader2
user4 Leader2
Transaction Table
-----------------------------------
User Leader Reason
-----------------------------------
user1 Leader1 Category 1 Reason 1
user1 Leader1 Category 1 Reason 1
user1 Leader1 Category 1 Reason 2
user1 Leader1 Category 1 Reason 2
user1 Leader1 Category 2 Reason 1
user1 Leader1 Category 2 Reason 1
user2 Leader1 Category 1 Reason 1
user2 Leader1 Category 1 Reason 1
user2 Leader1 Category 2 Reason 1
user2 Leader1 Category 2 Reason 1
我正在尝试计算用户进行的交易次数,并将其分为这两个类别。
我尝试了以下代码,该代码可以得到类别1原因的计数,但是仅显示具有该原因的用户。我的目的还在于向用户显示没有该原因但计数为0的用户。该查询也没有计算类别2原因(即使不打破这个简单的原因,我什至无法接近该值)
SELECT DISTINCT User.name, User.Leader, COUNT (reason) AS Reason FROM
Transactions AS TRACKER
INNER JOIN User AS GROUPS ON TRACKER.name=User.name
WHERE TRACKER.reason IN ('Category 1 Reason 1','Category 1 Reason 2','Category 1 Reason 3')
GROUP BY GROUPS.name, GROUPS.Leader
我的预期结果是:
--------------------------------------
User Leader Category 1 Category 2
--------------------------------------
User1 Leader1 4 2
User2 Leader1 2 2
User3 Leader2 0 0
User4 Leader2 0 0
但是我得到了:
-------------------------
User Leader Category 1
-------------------------
User1 Leader1 4
User2 Leader1 2
在此先感谢您的帮助
答案 0 :(得分:0)
我认为您需要条件聚合:
SELECT u.name, u.Leader,
SUM(CASE WHEN t.reason IN ('Category 1 Reason 1', 'Category 1 Reason 2', 'Category 1 Reason 3') THEN 1 ELSE 0 END) AS reason_count
FROM User u LEFT JOIN
Transactions t
ON t.name = u.name
GROUP BY u.name, u.Leader;
请注意,如果根本没有事务,这也将使用LEFT JOIN
将所有行保留在users
中。
如果出于每个类别的原因想要单独的列,请扩展上述逻辑:
SELECT u.name, u.Leader,
SUM(CASE WHEN t.reason IN ('Category 1 Reason 1') THEN 1 ELSE 0 END) as reason1_cnt,
SUM(CASE WHEN t.reason IN ('Category 1 Reason 2') THEN 1 ELSE 0 END) as reason2_cnt,
SUM(CASE WHEN t.reason IN ('Category 1 Reason 3') THEN 1 ELSE 0 END) as reason3_cnt
FROM User u LEFT JOIN
Transactions t
ON t.name = u.name
GROUP BY u.name, u.Leader;