仅限SQL Max值

时间:2015-11-03 15:00:36

标签: sql sql-server max

在以下脚本中,我希望BH_StartDate列仅返回最高日期值,因为它当前返回所有用户的所有日期值。是否可以使用此脚本仅包含最大日期值?

 SELECT         DISTINCT [dbo].[BH_Historic_Report_TaskAudit].BH_UserGuid       AS  'BighandUserGUID',
                BH_UserRole                                                     AS  'BighandUserRole',
                [dbo].[BH_Users].BH_FirstName                                   AS  'LastName',
                [dbo].[BH_Users].BH_Lastname                                    AS  'FirstName',
                [dbo].[BH_Users].BH_UserName                                    AS  'DisplayName',
                BH_StartDate                                                    AS  'StartDate', 
                [dbo].[BH_Users].BH_Description                                 AS  'JobDescription'

FROM            [dbo].[BH_Historic_Report_TaskAudit]
JOIN            [dbo].[BH_Users]
ON              [dbo].[BH_Historic_Report_TaskAudit].BH_UserGuid = [dbo].[BH_Users].BH_UserGuid
WHERE           BH_StartDate < '2015-04-29 00:00:00.000' AND BH_UserRole = 0 OR BH_UserRole = 2
ORDER BY        [dbo].[BH_Users].BH_LastName

2 个答案:

答案 0 :(得分:1)

我认为您可能在列别名中混合使用名字和姓氏。此外,当您在where子句中同时使用AND和OR时,您应该使用括号,以避免模糊主要合取/分离的位置。

我的想法是将计算列添加到BH_Historic_Report_TaskAudit以显示每个用户的最大BH_StartDate。此时可以进行日期过滤。 然后我们加入并过滤我们想要的角色,并要求BH_StartDate = max_BH_StartDate

SELECT DISTINCT 
  hrt.BH_UserGuid AS 'BighandUserGUID',
  hrt.BH_UserRole  AS  'BighandUserRole',
  bu.BH_FirstName  AS 'LastName',
  bu.BH_Lastname  AS 'FirstName',
  bu.BH_UserName AS 'DisplayName',
  hrt.BH_StartDate AS 'StartDate', 
  bu.BH_Description AS 'JobDescription'
FROM (
      select 
        BH_UserGuid, BH_UserRole, BH_StartDate,
        max(BH_StartDate) over (partition by BH_UserGuid) max_BH_StartDate 
      from [dbo].[BH_Historic_Report_TaskAudit] 
      where BH_StartDate < '2015-04-29 00:00:00.000'
      ) hrt
JOIN [dbo].[BH_Users] bu
ON hrt.BH_UserGuid = bu.BH_UserGuid
WHERE 
  (hrt.BH_UserRole = 0 OR hrt.BH_UserRole = 2)
     and
   hrt.BH_StartDate = hrt.max_BH_StartDate
ORDER BY  bu.BH_LastName 

答案 1 :(得分:0)

您还可以为所有记录创建2个#TempTable,即主表,并创建另一个表,以便从列中找出MAX值。然后更新Column IN主表。