如何加入静态值并将它们用作GROUP BY标识符?

时间:2015-02-13 11:54:50

标签: mysql group-by

我创建了一个SELECT语句,用于从现在到我数据库中的某个日期获取时差。

SELECT
    `username`,
    TIMESTAMPDIFF(HOUR, `a_date`, NOW()) AS `timediff`
FROM
    `User`

...会产生类似

的内容
username | timediff
-------------------
john     |      441
henry    |     1624
mike     |        4
kyle     |     NULL

现在我想将它们分组到预先定义的组中,例如

  • NULL
  • less than 20
  • greater than 20

如何使用一组静态预定义值JOIN上述结果,以及如何将这些值用作我的分组标识符?

group | amount
--------------
NULL  |      1
lt 20 |      1
gt 20 |      2

1 个答案:

答案 0 :(得分:1)

您可以将case语句与group by

一起使用
SELECT (CASE WHEN TIMESTAMPDIFF(HOUR, `a_date`, NOW()) < 20 THEN 'lt 20'
             WHEN TIMESTAMPDIFF(HOUR, `a_date`, NOW()) >= 20 THEN 'gt 20'
        END) as grp, COUNT(*)
FROM `User`
GROUP BY grp;

作为旁注:我通常会在case中重复group by语句,因为许多数据库不允许使用列别名:

SELECT (CASE WHEN TIMESTAMPDIFF(HOUR, `a_date`, NOW()) < 20 THEN 'lt 20'
             WHEN TIMESTAMPDIFF(HOUR, `a_date`, NOW()) >= 20 THEN 'gt 20'
        END) as grp, COUNT(*)
FROM `User`
GROUP BY (CASE WHEN TIMESTAMPDIFF(HOUR, `a_date`, NOW()) < 20 THEN 'lt 20'
               WHEN TIMESTAMPDIFF(HOUR, `a_date`, NOW()) >= 20 THEN 'gt 20'
          END);