代码之家  ›  专栏  ›  技术社区  ›  Jack Frost

带组的条件计数

  •  0
  • Jack Frost  · 技术社区  · 7 年前

    需要条件计数方面的帮助我无法显示报告所需的数据。我正在使用sql server 2008、sap crystal report

    我的代码

        SELECT c.Clients_Name
        ,COUNT(CASE 
                WHEN b.FI_result = 'Passed'
                    AND Date_applied >= @DS
                    AND Date_applied <= @DE
                    THEN 1
                END) AS [Jan]
        ,COUNT(CASE 
                WHEN b.FI_result = 'Passed'
                    AND Date_applied >= @DS
                    AND Date_applied <= @DE
                    THEN 1
                END) AS [Feb]
        ,COUNT(CASE 
                WHEN b.FI_result = 'Passed'
                    AND Date_applied >= @DS
                    AND Date_applied <= @DE
                    THEN 1
                END) AS [Mar]
    FROM Applicant_Operators AS a
    INNER JOIN Applicant_IS_History AS b ON a.Applicant_ID = b.Applicant_ID
    INNER JOIN Clients AS c ON b.Client_Name = c.Client_ID
    WHERE Date_applied >= @DS
        AND Date_applied <= @DE
    GROUP BY c.Clients_Name
    

    ` 代码显示

    Clients     Jan Feb Mar
    DENSO       14  14  14
    NPI         7   7   7
    MICROTOP    48  48  48
    

    我要显示的内容

    Clients     Jan Feb Mar
    DENSO       5   3   6
    NPI         2   1   4
    MICROTOP    10  20  18
    

    非常感谢您的帮助

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    你需要一些东西来确定月份。也许这正是您想要的:

    SELECT c.Clients_Name,
           SUM(CASE WHEN b.FI_result = 'Passed' AND
                         Date_applied >= @DS AND Date_applied <= @DE AND
                         MONTH(Date_applied) = 1
                    THEN 1 ELSE 0
               END) AS [Jan],
           . . .
    

    我更换了 count() 用一个 sum() 只是我个人对条件聚合的偏好。