SQL Server GROUP BY包含SELECT中的列但不包含GROUP BY子句中的列

时间:2015-08-05 01:23:02

标签: sql database database-administration

请帮我解决这个问题。

我有这个表格说明: Notes

我只想要这个显示: Highest note strength value, only 1 display if more than 1 same note strength value of distinct SubjectID and Stat

问题是有些音符具有相同的音符强度值。

3 个答案:

答案 0 :(得分:1)

SELECT n.ID
,n.SubjectID
,dbo.udf_StripHTML(ISNULL(n.Note,'')) AS [Note]
,n.[Note Strength Value]
FROM dbo.[Note] n INNER JOIN
(SELECT ID,SubjectID,Stat,MAX([Note Strength Value]) AS [Note Strength Value]
 FROM dbo.Note
 WHERE SeasonContext = 2015 AND Days in (99999, 7, 14, 30, 60, 90, 77777, 88888)
 GROUP BY ID,SubjectID,Stat) m  --added id in the group by clause
 ON n.ID = m.ID
WHERE n.SubjectID = 14463
ORDER BY n.[Note Strength Value] DESC

使用聚合函数时,如果未在该列上指定group by,则无法选择列。

答案 1 :(得分:0)

检查此解决方案。

function DemoSelect2(){
    var centerno = $(this).attr('data-centerno');
    $('#center').select2("val", centerno);
}

答案 2 :(得分:0)

SELECT ID,SubjectID,Stat,MAX([Note Strength Value]) AS [Note Strength Value] FROM dbo.Note WHERE SeasonContext = 2015 AND Days in (99999, 7, 14, 30, 60, 90, 77777, 88888) GROUP BY SubjectID,Stat)

更改为

SELECT ID,SubjectID,Stat,MAX([Note Strength Value]) AS [Note Strength Value] FROM dbo.Note WHERE SeasonContext = 2015 AND Days in (99999, 7, 14, 30, 60, 90, 77777, 88888) GROUP BY SubjectID,Stat,ID)

始终包含您在使用分组依据时选择的字段。