获得有条件的计数总和

时间:2013-05-10 18:05:14

标签: sql sql-server sql-server-2008 tsql

所以我试图得到一个有条件的计数的总和(与查询的其余部分不同)

这是我到目前为止所做的:

SELECT studemo.ssid                                 AS [SSID], 
       stustat.graden                               AS Grade, 
       studemo.lastname                             AS [Last Name], 
       studemo.firstname                            AS [First Name], 
       (SELECT Count(*) 
        WHERE  attend.attendc IN ( 'E', 'G', 'H', 'I', 
                                   'J', 'L', 'M', 'P', 
                                   'Q', 'V', 'X' )) AS [Days Absent], 
       attend.attendc                               AS [Attendance Code], 
       attend.ddate                                 AS [Date] 
FROM   track, 
       stustat, 
       stusched, 
       studemo, 
       attend 
WHERE  studemo.suniq = stustat.suniq 
       AND attend.scduniq = stusched.scduniq 
       AND studemo.suniq = stusched.suniq 
       AND stustat.trkuniq = track.trkuniq 
       AND track.schoolc = '408' 
       AND track.schyear = '2013' 
       AND stustat.edate >= '08/21/2012' 
       AND stustat.xdate IS NULL 
ORDER  BY [last name], 
          [first name], 
          attend.ddate 

这将为我提供正确的信息,而不是我试图获得它的方式。每个出勤代码都会给我一行。我希望做的只是将我从count(*)子查询中得到一些东西的次数加起来。我在大约100种不同的方式尝试过sum(),但我无法得到它。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

尝试替换该行:

(select count(*) where attend.attendc IN ('E','G','H','I','J','L','M','P','Q','V','X')) AS [Days Absent],

使用窗口功能:

sum(case when attend.attendc IN ('E','G','H','I','J','L','M','P','Q','V','X') then 1 else 0 end) over () as [Days Absent]

这是缺席的总天数。我猜你想要SSID。在这种情况下,请使用partition by

sum(case when attend.attendc IN ('E','G','H','I','J','L','M','P','Q','V','X') then 1 else 0 end)
          over (partition by SSID) as [Days Absent]