如何按年计算记录?

时间:2014-09-26 10:26:31

标签: php mysql

我需要记录一年的记录,我做了一些查询,但我没有得到正确的结果。以下是我的查询。但那不适合我。任何人都可以看看这个并给我正确的查询?任何帮助将不胜感激。

SELECT 
(SELECT count(DISTINCT id) FROM call_response WHERE  disposition=0 AND user_id=pu.id  ) AS `trueAlarm`, 
(SELECT count(DISTINCT id) FROM call_response WHERE  disposition=1 AND user_id=pu.id  ) AS `falseAlarm`, 
(SELECT count(DISTINCT id) FROM call_response WHERE  disposition=2 AND user_id=pu.id  ) AS `disregarded`, 
YEAR(cr.created_date) AS `callYear` 
FROM `call_response` AS `cr` 
INNER JOIN `permit_users` AS `pu` 
ON cr.user_id=pu.id 
WHERE ( pu.is_deleted=0 AND pu.is_trashed=0 AND cr.is_deleted=0)
GROUP BY `callYear`

1 个答案:

答案 0 :(得分:2)

您想要的查询使用条件聚合或子查询,但不能同时使用两者。换句话说,要么使用子查询,要么没有到call_response的外连接。或者,具有外部联接但不具有子查询。

我会写这样的查询:

SELECT count(distinct case when disposition = 0 AND user_id = pu.id then id end) as trueAlarm, 
       count(distinct case when disposition = 1 AND user_id = pu.id then id end) as falseAlarm, 
       count(distinct case when disposition = 2 AND user_id = pu.id then id end) as disregarded, 
       YEAR(cr.created_date) AS `callYear` 
FROM `call_response` `cr` INNER JOIN
     `permit_users` `pu` 
      ON cr.user_id = pu.id 
WHERE pu.is_deleted = 0 AND pu.is_trashed = 0 AND cr.is_deleted = 0
GROUP BY `callYear`;