2014-09-26 91 views
0

我需要計數記錄一年明智,我做了一些查詢,但我沒有得到正確的結果。以下是我的查詢。但是這對我沒有用。任何人都可以請看看這個,給我正確的查詢?任何幫助將不勝感激。如何統計全年的記錄?

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` 
+0

什麼是你期待?你有什麼?請在你的問題中更具體 – 2014-09-26 10:31:17

+1

你可以做一個SQL小提琴(http://sqlfiddle.com/)? – 2014-09-26 10:31:23

+0

從你提供的信息來看,我的猜測是針對這些不同的選擇。 是否刪除所有3個請求返回的東西? – Cyrbil 2014-09-26 10:33:37

回答

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`; 
+1

+1,儘管如此,但你把它放在更好的單詞中;) – Cyrbil 2014-09-26 11:16:09