【问题标题】:How can I do a query with Count + Distinct+When?如何使用 Count + Distinct+When 进行查询?
【发布时间】:2014-11-20 13:33:36
【问题描述】:

我有这张表(tableName):

|            IdPerson  | Date       | idPerson      |          idControls | Status
|                  125 | 2014-11-01 |           106 |                   4 | 1     |
|                  126 | 2014-12-01 |           109 |                   3 | 0     |
|                  127 | 2014-13-01 |           112 |                   2 | 1     |
|                  128 | 2014-14-01 |           115 |                   4 | 0     |
|                  129 | 2014-14-01 |           118 |                   3 | 0     |
|                  130 | 2014-16-01 |           121 |                   4 | 1     |

我在执行这些查询时得到了正确的结果:

QUERY1:

select Date,count(distinct idControls) from tableName where Status=0 group by Date;
+------------+-------------------------------------+
| Date       | count(distinct idControls)          |
+------------+-------------------------------------+
| 2014-12-01 |                                   1 |
| 2014-14-02 |                                   2 |

查询2:

select Date,count(distinct idControls) from tableName where Status=1 group by Date;
+------------+-------------------------------------+
| Date       | count(distinct idControls)          |
+------------+-------------------------------------+
| 2014-11-01 |                                   1 |
| 2014-13-02 |                                   1 |
| 2014-16-02 |                                   1 |

但是,我想做的是将两个查询都包含在一个查询中。

然后,我正在尝试做这样的事情:

 select Date,sum(distinct(idControls) case when Status='1' then 1  else 0 end) fail ,sum(distinct case when Status='0' then 1 else 0 end) correct from tableName group by Date;

显然,上面的查询不起作用....

有什么想法吗?

【问题讨论】:

    标签: mysql count case distinct


    【解决方案1】:

    稍微不同的方法是

    SELECT `Date`,
           `status`,
           COUNT(DISTINCT `idControls`)
    FROM `tableName` 
    GROUP BY `Date`, `status`;
    

    更简单的查询,但每个日期有两个结果行而不是一个。

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      相关资源
      最近更新 更多