MySQL通过不返回正确的结果来计数

时间:2016-06-23 17:55:21

标签: mysql sql count group-by mariadb

我有一个票务系统,我正在尝试运行报告。我试图获得每位用户触及的门票数量。 通过第一个查询:

SELECT * FROM (
SELECT TicketID, UserID, EventDateTime
FROM dcscontact.ticketevents
WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
ORDER BY EventDateTime DESC) x
WHERE UserID=80
GROUP BY TicketID;

我可以列出为特定用户触摸的门票,并可以手动计算:

TicketID    UserID  EventDateTime
99168       80      6/22/2016 13:21
99193       80      6/22/2016 7:42
99213       80      6/22/2016 13:02
99214       80      6/22/2016 6:30
99221       80      6/22/2016 6:57
99224       80      6/22/2016 7:48
99226       80      6/22/2016 6:27
99228       80      6/22/2016 8:49
99229       80      6/22/2016 8:53
99232       80      6/22/2016 9:18
99237       80      6/22/2016 13:08

但是当我尝试删除WHERE UserID =语句时,尝试将其用作子查询,如下所示:

SELECT UserID, COUNT(*) as count FROM (
    SELECT * FROM (
    SELECT TicketID, UserID, EventDateTime
    FROM dcscontact.ticketevents
    WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
    ORDER BY EventDateTime DESC) x
    GROUP BY TicketID) y
GROUP BY UserID;

我的计数不正确:

UserID  count
9       2
28      1
31      1
42      1
80      5
95      1
99      6
108     4
116     12
117     26
123     24

正如您所看到的,UserID 80的计数应为11.其他大多数结果也不正确,它们似乎都比我预期的数字更低。

在子查询上使用GROUP BY / COUNT时,我做错了吗?如何更改查询以获得我想要的结果?

2 个答案:

答案 0 :(得分:3)

您只想要聚合吗?

SELECT UserID, COUNT(*)
FROM dcscontact.ticketevents
WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
GROUP BY UserID;

如果同一个故障单可以在给定用户的数据中出现多次,那么COUNT(DISTINCT)更合适:

SELECT UserID, COUNT(DISTINCT TicketID)
FROM dcscontact.ticketevents
WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
GROUP BY UserID;

答案 1 :(得分:0)

要获取每位用户触摸的门票数量,请让我们从正确的查询开始:

SELECT count(*) as N, UserID
FROM dcscontact.ticketevents
WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
GROUP BY UserID;

GROUP BY子句应始终包含SELECT子句中提到的所有非聚合列。询问"机票ID和机票数量(每个用户)"!

是没有意义的。

此外,SQL标准说ORDER BY不能应用于子查询。最好将ORDER BY视为查看输出的便利,而不是查询中使用的信息。

您还想了解TicketIDEventDateTime的相关信息。您无法询问"门票数量的ID",但您可以获得第一张和最后一张票。时间相同:

SELECT   count(*) as N
       , min(TicketID) as T1
       , max(TicketID) as Tn
       , min(EventDateTime) as E1
       , max(EventDateTime) as En
   , UserID
FROM dcscontact.ticketevents
WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
GROUP BY UserID;

请注意,最早的时间可能不是最小TicketID的时间。要获取有关每个用户的第一张票的所有内容以及计数,请加入以下两个信息来源:

select N.N, T.* 
from dcscontact.ticketevents as T
join (
    SELECT count(*) as N, min(TicketID) as T1, UserID
    FROM dcscontact.ticketevents
    WHERE EventDateTime BETWEEN '2016-06-22' AND '2016-06-23'
    GROUP BY UserID;
) as N
on  T.UserID = N.UserID 
and T.TicketID = N.TicketID
-- and maybe others, according to the key
order by EventDateTime DESC