我创建了一个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
答案 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);