0

我想在我的查询中获得最高值

Select SUM(CASE WHEN Day='Monday' THEN 1 END) AS'Total Monday',
       SUM(CASE WHEN Day='Tuesday' THEN 1 END) AS'Total Tuesday'  
FROM tbl_sched 
WHERE teacherID='2014279384'

输出将是 TotalMonday ='1' 和 TotalTuesday ='2'
我需要从输出中获得最高值,在这种情况下是 TotalTuesday=2

4

5 回答 5

1
select max(daycnt) from
(Select SUM(CASE WHEN Day='Monday' THEN 1 END) AS daycnt
 from tbl_sched WHERE teacherID='2014279384'
union all
Select SUM(CASE WHEN Day='Tuesday' THEN 1 END) AS daycnt
 from tbl_sched WHERE teacherID='2014279384')
于 2014-12-03T14:38:49.933 回答
1

如果您需要多列之间的最大值:

有趣的SQLServer 2008东西

SELECT  (SELECT Max(v) 
FROM (VALUES ([Total Monday]), ([Total Tuesday]), ...) AS value(v)) as [MaxDate]
From
(   
    Select SUM(CASE WHEN Day='Monday' THEN 1 END) AS'Total Monday',
           SUM(CASE WHEN Day='Tuesday' THEN 1 END) AS'Total Tuesday'  
            ..........
    FROM tbl_sched 
    WHERE teacherID='2014279384'
    )a  

另外的选择:

SELECT Case When [Total Monday] > [Total Tuesday] then [Total Monday] else [Total Tuesday] End as maxvalue
FROM 
(   
    Select SUM(CASE WHEN Day='Monday' THEN 1 END) AS'Total Monday',
           SUM(CASE WHEN Day='Tuesday' THEN 1 END) AS'Total Tuesday'  
    FROM tbl_sched 
    WHERE teacherID='2014279384'
    )a
于 2014-12-03T14:43:36.997 回答
0

我想说下面的查询在性能方面更好,并且更好地突出了意图,因为基本上我们只是按天分组并计数组,我们不需要 CASE 或 SUM(在这种情况下 SQL Server 将不得不去所选教师的所有记录)。

SELECT   TOP 1 Day, COUNT(*) AS Total
FROM     tbl_sched 
WHERE    teacherID='2014279384'
AND      Day IN ('Monday','Tuesday')
GROUP BY Day
ORDER BY Total DESC
于 2014-12-03T15:03:22.057 回答
0

您可以按分组Day、排序COUNT(*) DESC并获得最高计数:

SELECT TOP (1)
  TotalCount = COUNT(*)
FROM
  dbo.tbl_sched
WHERE
  teacherID = '2014279384'
GROUP BY
  Day
ORDER BY
  TotalCount DESC
;

您还可以包含Day在输出中以返回具有最高结果的日期。

于 2014-12-10T10:14:46.210 回答
-1

您可以通过使用 Max Function 来实现

Select MAX(SUM(CASE WHEN Day='Monday' THEN 1 END)) AS 'Total Monday',
   MAX(SUM(CASE WHEN Day='Tuesday' THEN 1 END)) AS 'Total Tuesday'  
FROM tbl_sched 
WHERE teacherID='2014279384'
于 2014-12-03T14:38:55.913 回答