SELECT中的SQL Max()会导致行中的值不正确

SELECT中的SQL Max()会导致行中的值不正确,sql,sql-server,tsql,group-by,max,Sql,Sql Server,Tsql,Group By,Max,SQL查询: WITH Instructors AS ( SELECT DISTINCT dimUser.EmpFK, Usr.Usr_Name AS UserID, dimUser.EmpFullName3, dimUser.PrimaryOrgName, dimUser.EmpCity, dimUser.EmpPhn1, dimUser.EmpUrl, dimUser.PrimaryJobName, dimUser.EmpState, dimUser.EmpAdd2 FROM fa

SQL查询:

WITH Instructors AS (
SELECT DISTINCT 
dimUser.EmpFK, 
Usr.Usr_Name AS UserID, 
dimUser.EmpFullName3, 
dimUser.PrimaryOrgName,
dimUser.EmpCity,
dimUser.EmpPhn1,
dimUser.EmpUrl,
dimUser.PrimaryJobName,
dimUser.EmpState,
dimUser.EmpAdd2

FROM factResourceInstructor FRI
LEFT JOIN dimUser 
ON dimUser.ID = FRI.InstID
LEFT JOIN Iwc_Usr Usr 
ON dimUser.EmpFK = Usr.Usr_empFK)

SELECT
MAX(Instructors.EmpFullName3) as N'Name',
MAX(Instructors.PrimaryOrgName) as N'Group/Function',
MAX(Instructors.EmpCity) as N'Region',
MAX(Instructors.EmpPhn1) as N'Division',
MAX(Instructors.empurl) as N'Office',
MAX(Instructors.PrimaryJobName) as N'Job',
class.ActivityName as N'Class Name',
dimActivity.ActivityLabel as N'ActivityType',
MAX(Activity.ActivityName) as N'Session Name',
--dimActivity.EstDurHours as N'Estimated Duration',
CASE 
  WHEN SUM(Attempt.ElapsedSeconds) IS NOT NULL 
  THEN SUM(Attempt.ElapsedSeconds) / 3600 ELSE 0 
END AS 'Estimated Duration',
Activity.StartDt as N'Activity Start Date (UTC)',
DateAdd(millisecond,  
        ISnull((select RawOffset 
                from tbl_lms_TimeZoneData 
                where TimeZone_FK = (MAX(dimActivity.TimeZoneFK))
                )
        ,0) 
, DateAdd(millisecond,  
         ISnull((select Offset 
                 from tbl_lms_ConvertTimeZoneData 
                 where TimeZone_FK = (MAX(dimActivity.TimeZoneFK)) 
                 and MAX(dimActivity.StartDt) between StartDate and EndDate),
         0)
, MAX(dimActivity.StartDt))) as N'Activity Start Date'

FROM Instructors
LEFT JOIN TBL_TMX_Attempt Attempt 
ON Instructors.EmpFK = Attempt.EmpFK
LEFT JOIN TBL_TMX_Activity Activity 
ON Attempt.ActivityFK = Activity.Activity_PK
LEFT JOIN dimActivity 
ON Activity.Activity_PK = dimActivity.ActivityFK
INNER JOIN dimActivity class 
on class.ActivityFK = dimActivity.RootActivityFK

GROUP BY class.ActivityName
, dimActivity.ActivityLabel
, Activity.StartDt
ORDER BY Name
返回用户和作业的列表。每个用户可以出现在多行上,但偶尔一个用户可以在不同行的“作业”列中具有不同的值。为什么会发生这种情况?我怎样才能阻止它?如果这些信息有帮助,我正在使用Microsoft SQL Server。不幸的是,由于查询需要使用的软件,我无法使用子查询

我没有SQL方面的经验,也没有最初编写此查询。
感谢您的帮助。

您的分组方式列表中有此列:

Instructors.PrimaryJobName
然而,此列在您的选择列表中显示为聚合(这意味着它不应该在GROUP BY列表中,或者它不应该被聚合-我们不知道这是什么,除了几乎可以肯定是字符串的值上的MAX()似乎没有太多意义)


请尝试从“分组依据”列表中删除该列,或者不在“选择”列表中对其应用MAX(),然后查看结果是否正确。

在“分组依据”列表中使用“Instructors.PrimaryJobName”只是我更改文件以查看是否可行时的一个错误。删除MAX()确实可以解决出现错误“Job”值的问题,但也会导致查询返回比以前更多的行。这可能是最初的意图,而前一位作者只是犯了一个错误。也许你应该重新开始这个查询。向我们展示示例数据(例如使用SQLFIDLE)和所需结果。逆向工程——你必须尝试找出你可能期望的是什么——是很麻烦的。。。