GROUP BY中的T-SQL额外列。如何包含在结果中但从分组中排除

时间:2010-11-22 13:43:31

标签: sql-server group-by

我有以下SQL

SELECT     CNumber, MAX(FormSubmitted), Score
FROM         dbo.vw_MSA
WHERE     (Score IS NOT NULL)
GROUP BY CNumber, Score

结果:

CNumber FormSubmitted                   Score
0011509 2010-09-13 10:22:46.763         11
0016239 2010-09-28 13:53:58.557         8*
0016239 2010-10-12 11:52:33.150         12
0018792 2010-11-02 13:17:37.437         3
0051089 2010-10-07 11:38:29.257         13
0051091 2010-10-01 12:01:30.450         0
0067987 2010-09-29 11:06:48.490         7
0079351 2010-09-30 09:49:10.747         34
0833933 2010-09-30 12:54:19.013         6
0848185 2010-10-07 12:08:42.087         6
5010590 2010-11-01 09:54:14.790         6*
5010590 2010-11-16 15:23:50.350         12

我确信我应该能够轻松地对此进行排序,但无论出于何种原因,我都在努力解决这个问题。我需要在结果中包含分数,但在GROUP BY中使用分数不可避免地返回的不仅仅是具有最新FormSubmitted日期的记录。任何人都可以帮助我更新这个查询,所以我会得到结果中的分数,但只有那些最大的FormSubmitted日期的记录,即排除那些标记*?

2 个答案:

答案 0 :(得分:2)

假设(CNumber, FormSubmitted)保证唯一:

SELECT T1.CNumber, T1.FormSubmitted, T1.Score
FROM dbo.vw_MSA T1
JOIN
(
    SELECT CNumber, MAX(FormSubmitted) AS MaxFormSubmitted
    FROM dbo.vw_MSA
    WHERE Score IS NOT NULL
    GROUP BY CNumber
) T2
ON T1.CNumber = T2.CNumber
AND T1.CNumber = T2.MaxFormSubmitted

答案 1 :(得分:1)

SELECT     A.CNumber, A.FormSubmitted, A.Score
FROM         dbo.vw_MSA A
INNER JOIN 
(SELECT CNumber, MAX(FormSubmitted) AS MaxSubmitted 
FROM dbo.vw_MSA
WHERE     (Score IS NOT NULL)
GROUP BY CNumber) AS B
ON A.CNumber = B.CNumber AND A.FormSubmitted = B.MaxSubmitted