选择与计算匹配的行

时间:2012-03-28 11:21:27

标签: mysql sql

我有这个查询来计算一周和几小时中最常见的日子:

SELECT
  DATE_FORMAT(DATE, '%a') AS wd,
  HOUR(DATE) AS hr,
  COUNT(*) AS cnt
FROM 
 users
GROUP BY
  wd, hr
ORDER BY
  cnt DESC

现在,我想选择与wd = "Fri" AND hr = "9"

匹配的所有行的ID

我已经尝试添加WHERE子句,但我不能,因为我不能在别名上使用WHERE

2 个答案:

答案 0 :(得分:1)

SELECT ID
FROM   users
WHERE  DATE_FORMAT(DATE, '%a') = 'Fri' AND HOUR(DATE) = 9

答案 1 :(得分:0)

SELECT
  DATE_FORMAT(DATE, '%a') AS wd,
  HOUR(DATE) AS hr,
  COUNT(*) AS cnt
FROM users
WHERE DATE_FORMAT(DATE, '%a') = 'Fri'
AND HOUR(DATE) = 9
GROUP BY wd, hr
ORDER BY cnt DESC

您也可以使用别名选择来执行此操作,但性能一样好,因为这种方式在聚合之前发生