具有条件

时间:2016-08-14 00:14:02

标签: mysql count

我有一张这样的表:

+---------------+--------+-----------------+
| ReservationID | UserID | ReservationDate |
+---------------+--------+-----------------+
|             1 |  10002 | 04_04_2016      |
|             2 |  10003 | 04_04_2016      |
|             3 |  10003 | 07_04_2016      |
|             4 |  10002 | 04_04_2016      |
|             5 |  10002 | 04_04_2016      |
|             6 |  10002 | 06_04_2016      |
+---------------+--------+-----------------+

我使用此查询来计算我的每个用户有多少预订:

SELECT UserID, COUNT(UserID) as Times FROM mytable GROUP BY UserID ORDER BY Times DESC

它给了我这个结果:

+--------+-------+
| UserID | Times |
+--------+-------+
|  10002 |     4 |
|  10003 |     2 |
+--------+-------+

但是,如果我的用户在特定日期有多个预订,我想要计算一个。例如,用户10002在04-04-2016有3个预订,应该是1个。我希望得到这个结果:

+--------+-------+
| UserID | Times |
+--------+-------+
|  10002 |     2 |
|  10003 |     2 |
+--------+-------+

我怎样才能得到它?

由于

2 个答案:

答案 0 :(得分:0)

使用count代替distinct

SELECT UserID, COUNT(DISTINCT ReservationDate) as Times 
FROM mytable 
GROUP BY UserID 
ORDER BY Times DESC

答案 1 :(得分:0)

SELECT 
  m.UserID,
  count(distinct lj.ReservationDate) as Times 
FROM mytable m
  left join mytable lj on lj.UserID = m.UserId
GROUP BY 
  m.UserId
ORDER BY 
  Times 
相关问题