简体   繁体   中英

count where and if, within a select statement

Hi I am trying to write a stacked bar chart in mysql, and first I need to get the query right, and need some help.

Currently I have:

SELECT
COUNT(TargetDate) AS Planned,
COUNT(StartDate) AS Completed,
MONTHNAME(TargetDate) AS `Month`,
StartDate,
AssessmentStatus
FROM AuditCycleAssessments
WHERE (Year(TargetDate) = Year(now()))
GROUP BY MONTHNAME(TargetDate)
ORDER BY Month(TargetDate)

which works just fine and looks like screenshot

However I need to change the 3rd line to include its own where statement, something like...

  (COUNT(StartDate) if AssessmentStatus=3) AS Completed,

So number 1, can someone help me achieve this.

Thanks

check how to write IF But here you can not write if you should use CASE

SELECT
COUNT(TargetDate) AS Planned,
COUNT(CASE WHEN AssessmentStatus=3 THEN StartDate END) AS Completed,
MONTHNAME(TargetDate) AS `Month`,
StartDate,
AssessmentStatus
FROM AuditCycleAssessments
WHERE (Year(TargetDate) = Year(now()))
GROUP BY MONTHNAME(TargetDate)
ORDER BY Month(TargetDate)

Do a conditional COUNT with a CASE statement

SELECT
    COUNT(TargetDate) AS Planned,
    COUNT(CASE WHEN AssessmentStatus=3 THEN StartDate END) AS Completed,
    MONTHNAME(TargetDate) AS `Month`,
    StartDate,
    AssessmentStatus
FROM AuditCycleAssessments
WHERE (Year(TargetDate) = Year(now()))
GROUP BY MONTHNAME(TargetDate)
ORDER BY Month(TargetDate)

类似于以下内容的内容可能会为您服务,未经您的情况测试,但它应该可以工作。

Sum(IIf([AssessmentStatus]=3 AND [StartDate] NOT IS NULL,1,0)) AS Completed,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM