我必须从表中获取每周报告,其中每个记录的状态如1表示打开,2表示关闭,因此我使用周作为按键分组,并使用案例条件进行差异计数,如打开,关闭,红色等,但数据不是我想要的准确。 您将更好地支持下面提到的查询。 每个回复都被拨出。
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
答案 0 :(得分: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)
,如果不是,则评估为COUNT(NULL)
,这是0。
您还可以使用SUM()
:
SUM(CASE WHEN <Condition> THEN 1 ELSE 0 END)