SQL 在 SELECT 中包含列但不在 GROUP BY 子句中的服务器 GROUP BY

SQL Server GROUP BY that include column in SELECT but not in GROUP BY clause

请帮我解决这个问题。

我有这个 table 注释: Notes

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

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

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,则不能 select 列。

检查这个解决方案。

WITH Note_Max AS
(
    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  n.ID
        ,n.SubjectID
        ,dbo.udf_StripHTML(ISNULL(n.Note,'')) AS [Note]
        ,n.[Note Strength Value]
FROM    Note n 
INNER JOIN
        n.ID = Note_Max.ID
WHERE   n.SubjectID = 14463
ORDER BY n.[Note Strength Value] DESC

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)

在使用分组依据时总是包含您 select 的字段。