我有一张表,其中包含经理和日期的操作。行动可以是"0" or "1"
。
我希望按日期分组并计算按日期和经理分组的"0" and "1"
次操作。
这是我的代码。
SELECT COUNT( * ) ,
manager_id,
action,
CAST( `created_at` AS DATE ) AS DATE
FROM `prerequesttours_history`
GROUP BY CAST( `created_at` AS DATE ),
anager_id,
action
我想这样结果:
| count where action = 1 | count where action = 0 | manager_id | date
答案 0 :(得分:0)
尝试将其选为子查询。
SELECT SUM([Count]), manager_id, action, [Date]
FROM
(
SELECT COUNT( * ) 'Count' , manager_id, action, CAST( `created_at` AS DATE ) 'Date'
) main
GROUP BY manager_id, action, [Date]
答案 1 :(得分:0)
如果action
仅使用这两个值,则可以执行以下操作:
SELECT manager_id, date(`created_at`) AS DATE,
SUM(action) as count_1, SUM(1 - action) as cnt_0
FROM `prerequesttours_history`
GROUP BY manager_id, date(created_at);
如果您想更明确地比较:
SELECT manager_id, date(`created_at`) AS DATE,
SUM(action = 1) as count_1, SUM(action = 1) as cnt_0
FROM `prerequesttours_history`
GROUP BY manager_id, date(created_at);
注意:使用cast()
转换为日期很好。但是,MySQL为此目的提供了更简单的函数date()
。