2017-09-14 67 views
1

我必須從表格中獲取每週報告,每個記錄的狀態如1表示爲開放狀態,2表示關閉狀態,所以我使用周作爲組的鍵和用於差異計數的使用情況(如開放,封閉,紅色等,但數據並不準確,因爲我想。 你會更好地支持下面提到的查詢。 每個響應都已撥出。有條件的計數MySQL

SELECT DISTINCT discussion_date,department,DAYNAME(discussion_date) AS DAY,CONCAT(YEAR(discussion_date),'/',WEEK(discussion_date)) AS week_name,YEAR(discussion_date) AS YEAR,CONCAT('WEEK -', WEEK(discussion_date)) AS week_no,COUNT(*) as total_queries,(CASE WHEN review_items.status = 1 AND due_date > curdate() THEN count(*) ELSE 0 END) as open,(CASE WHENreview_items.status = 2 THEN count(*) ELSE 0 END) as closed,(case when manager_closuredate > due_date THEN count(*) ELSE 0 END) as red,(CASE WHEN review_items.status = 3 THEN count(*) ELSE 0 END) as hold,(CASE WHEN review_items.status = 4 THEN count(*) ELSE 0 END) as discussion,DATE_ADD(discussion_date,INTERVAL(2 - DAYOFWEEK(discussion_date)) DAY) AS Week_start_date,DATE_ADD(discussion_date,INTERVAL(7 - DAYOFWEEK(discussion_date)) DAY) AS Week_end_date,DAYNAME(DATE_ADD(discussion_date,INTERVAL(2 - DAYOFWEEK(discussion_date)) DAY)) AS WeeK_Start_DAY FROM review_items 
WHERE department = 'Development' AND discussion_date BETWEEN '2017-08-01' AND '2017-08-31' 
GROUP BY week_name 
ORDER BY YEAR (discussion_date) ASC,WEEK(discussion_date) ASC 

回答

1

您沒有正確使用條件聚合:

COUNT(CASE WHEN review_items.status = 1 AND due_date > curdate() THEN 1 END) as open, 
COUNT(CASE WHEN review_items.status = 2 THEN 1 END) as closed, 
COUNT(case when manager_closuredate > due_date THEN 1 END) as red, 
COUNT(CASE WHEN review_items.status = 3 THEN 1 END) as hold, 
COUNT(CASE WHEN review_items.status = 4 THEN 1 END) as discussion, 

可以既COUNT和使用的值,該列是任一種聚合溫控功能,或不是,不能同時使用。

所以我們的想法是隻有在條件滿足的情況下,纔會給計數器加1。有幾種方法可以做到這一點,其中一個是COUNT(),如果條件滿足,則評估爲COUNT(1),即1。如果不滿足,則評估爲COUNT(NULL),即0。

您還可以使用SUM()

SUM(CASE WHEN <Condition> THEN 1 ELSE 0 END) 
+0

是它的工作,謝謝@sagi。 –