MySQL - 将两列中具有相等值的多行视为一行

MySQL - Consider multiple rows with equal value in two columns as one row

假设我有一个包含以下数据的 table:

Event_ID | Action_ID | Date_of_Action

   1     |     1     |  2015-06-25
   2     |     1     |  2015-06-25
   3     |     1     |  2015-04-10
   4     |     2     |  2015-05-11

我需要获取此 table 中具有特定 Action_ID 的行数并显示它们,但我需要处理具有相同 Action_ID 和 Date_of_Action 作为 1 行(或 1 个计数)。

我希望它显示:

Count 1  | Count 2
         |
   2     |    1         

我试过这个:

SELECT 
SUM(IF(event.Action_ID = 1, 1, 0)) AS 'Count 1',
SUM(IF(event.Action_ID = 2, 1, 0)) AS 'Count 2',
...
GROUP BY event.Action_ID, event.Date_of_Action

但我的输出看起来像这样:

Count 1  | Count 2
         |
   3     |   1

有什么想法吗?

我首先要获得不同的 action_id 和日期对,如下所示:

SELECT DISTINCT action_id, date_of_action
FROM myTable;

一旦你有了它,你就可以使用条件聚合来计算:

SELECT SUM(action_id = 1) AS 'count 1', SUM(action_id = 2) AS 'count 2'
FROM(
   SELECT DISTINCT action_id, date_of_action
   FROM myTable) tmp;

这是一个 SQL Fiddle 示例。

使用组合具有相同操作 ID 和日期的行的子查询:

SELECT 
SUM(IF(event.Action_ID = 1, 1, 0)) AS 'Count 1',
SUM(IF(event.Action_ID = 2, 1, 0)) AS 'Count 2',
...
FROM (SELECT DISTINCT Action_ID, Date_of_Action
      FROM event) AS event

您真的需要将它们放在单独的列中,还是只是您需要的数据? 如果您对每次计数一行感到满意,请尝试

SELECT Action_ID, count(Event_ID)
FROM myTable
group by Action_ID, Date_of_Action