在SQL Server中获取Max和计数

时间:2014-12-03 22:30:13

标签: sql-server

我希望获得与最大假期相关的最大假日列和ID ...如何调整查询?

select cal.schoolid,count(d.instruction) as holiday 
    from day d 
    inner join calendar cal on d.calendarID=cal.calendarID
    inner join schoolyear sy on sy.endyear=cal.endyear and sy.active=1
    where d.instruction=0 
    group by cal.schoolid

这是结果:

ID  Holidays
237 86
240 86
261 168
262 168
264 155
266 168
267 170

3 个答案:

答案 0 :(得分:2)

使用Top 1获取Max Holiday

SELECT TOP 1 cal.schoolid,
                Count(d.instruction) AS holiday
         FROM   [day] d
                INNER JOIN calendar cal
                        ON d.calendarID = cal.calendarID
                INNER JOIN schoolyear sy
                        ON sy.endyear = cal.endyear
                           AND sy.active = 1
         WHERE  d.instruction = 0
         GROUP  BY cal.schoolid
ORDER  BY Holiday DESC

或使用Window Function

;WITH cte
     AS (SELECT cal.schoolid,
                Count(d.instruction) AS holiday
         FROM   [day] d
                INNER JOIN calendar cal
                        ON d.calendarID = cal.calendarID
                INNER JOIN schoolyear sy
                        ON sy.endyear = cal.endyear
                           AND sy.active = 1
         WHERE  d.instruction = 0
         GROUP  BY cal.schoolid)
SELECT ID,
       Holidays
FROM  (SELECT Row_number()OVER (ORDER BY Holidays DESC) rn,*
       FROM   cte) A
WHERE  rn = 1 

答案 1 :(得分:1)

结果与您选择的结果有所不同(我的意思是列名称)。无论如何,请使用MAX()

select cal.schoolid,MAX(count(d.instruction)) as holiday 
from day d 
inner join calendar cal on d.calendarID=cal.calendarID
inner join schoolyear sy on sy.endyear=cal.endyear and sy.active=1
where d.instruction=0
group by cal.schoolid

答案 2 :(得分:1)

 select schoolid, max(holiday) from( select cal.schoolid,count(d.instruction) as
holiday 
from day d 
inner join calendar cal on d.calendarID=cal.calendarID
inner join schoolyear sy on sy.endyear=cal.endyear and sy.active=1
where d.instruction=0 
group by cal.schoolid) group by schoolid