在select语句中计算where和if

时间:2017-05-17 14:25:02

标签: mysql

您好我正在尝试在mysql中编写堆积条形图,首先我需要正确查询,并需要一些帮助。

目前我有:

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)

效果很好,看起来像screenshot

但是我需要更改第3行以包含其自己的where语句,例如......

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

所以1号,有人可以帮我实现这个目标。

由于

3 个答案:

答案 0 :(得分:1)

检查如何写IF但是如果你应该使用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)

答案 1 :(得分:1)

使用COUNT语句

执行条件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)

答案 2 :(得分:0)

以下内容可能会为您提供服务,未经您的方案测试,但它应该可以正常工作。

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