条件计数与组

时间:2018-01-08 05:11:08

标签: sql sql-server-2008 stored-procedures crystal-reports

需要条件计数方面的帮助我无法显示报告所需的数据。我正在使用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 个答案:

答案 0 :(得分:0)

您需要一些东西来识别月份。也许这就是你想要的:

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()仅仅是我个人对条件聚合的偏好。