2014-12-03 59 views
0

我想在我的查詢獲得最高的價值在不同的選擇SUM

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

回答

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') 
-1

可以通過使用最大函數

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' 
達到這個最高值
+0

這將給出與問題中完全相同的內容。我認爲這是錯誤的 – mounaim 2014-12-03 14:41:22

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 
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 
0

你可以通過Day組,排序COUNT(*) DESC並獲得最高計:

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

還可以包括Day到輸出到返回了最上面的結果的一天。