分组一些数据

时间:2017-08-28 13:12:50

标签: php mysql sql

我有一个SQL查询:

SELECT COUNT(id) AS number_plays, id
FROM table
WHERE date_play >= '2017-08-27 00:00:00' AND date_play <= '2017-08-27 23:59:59'
GROUP BY id, date_play
HAVING number_plays > 1
ORDER BY number_plays DESC

结果就像是:

number_plays                id
20                          15
40                          15
32                          18
20                          15

是否可以按播放次数对此结果进行分组?最终结果如下:

iterations                 number_plays          id
2                          20                    15
1                          40                    15
1                          32                    18

我可以得到一些帮助吗?提前谢谢。

1 个答案:

答案 0 :(得分:3)

两件事 - 首先,如果在GROUP BY子句中指定一列,请尝试在SELECT内指定它。只有MySQL允许这样做,我发现它错了并且可能引发错误/输出错误的数据,你不会理解为什么。

其次,只需用另一个查询包装查询,并将number_plays添加到GROUP BY子句中:

SELECT count(*) as iterations,t.number_plays,t.id
FROM(
    SELECT  id,date_play,COUNT(id) AS number_plays,
    FROM table
    WHERE date_play >= '2017-08-27 00:00:00' 
      AND date_play <= '2017-08-27 23:59:59'
    GROUP BY id, date_play
    HAVING number_plays > 1
    ORDER BY number_plays DESC) t
GROUP BY t.number_plays,t.id