在查询中添加非聚合列

时间:2017-04-26 09:30:05

标签: sql sql-server sql-server-2012

我必须在下面的查询中添加名为“Number3”的列。但它是一个非聚合列,如果添加到select语句和group by子句,则会更改结果。

如何获得相同的结果并在查询中添加名为“Number3”的列而不将其添加到group by子句中?

select distinct [Name], 
max([ArchiveDT]) as [ArchiveDT],
Number1,
Number2
FROM Table
where ArchiveDT>=dateadd(day, datediff(day, 0, getdate()-1), 0) and
  ArchiveDT<dateadd(day, datediff(day, 0, getdate()), 0)
  and [Name] is not null
group by [Name] ,Number1,Number2

3 个答案:

答案 0 :(得分:1)

使用以下查询:

 SELECT  A.[Name] , A.[ArchiveDT] , A.Number1,A.Number2,O.NUmber3
 FROM [SAEI].[dbo].[ArchiveMessages_ACARS] O
 JOIN 
 (
    SELECT DISTINCT [Name],MAX([ArchiveDT]) as [ArchiveDT],
        Number1,Number2
    FROM [SAEI].[dbo].[ArchiveMessages_ACARS]
    WHERE ArchiveDT>=dateadd(day, datediff(day, 0, getdate()-1), 0) and
       ArchiveDT<dateadd(day, datediff(day, 0, getdate()), 0)
       and [Name] is not null
    GROUP BY [Name] ,Number1,Number2
  ) A ON A.[Common_value] = O.[Common_value]

答案 1 :(得分:0)

如果要将列添加到聚合查询中 您要么将其添加到GROUP BY 如果这不符合您的预期结果,您将必须使用聚合函数 如果您希望它出现,请与SUMAVGMINMAX一样。

在你的例子中,它可以给出类似的东西:

select distinct [Name], 
max([ArchiveDT]) as [ArchiveDT],
Number1,
Number2,
MAX(Number3)
FROM [SAEI].[dbo].[ArchiveMessages_ACARS]
where ArchiveDT>=dateadd(day, datediff(day, 0, getdate()-1), 0) and
  ArchiveDT<dateadd(day, datediff(day, 0, getdate()), 0)
  and [Name] is not null
group by [Name] ,Number1,Number2

答案 2 :(得分:0)

您可以查看使用派生表,但只有在派生表中有唯一标识符时才会起作用,例如:

SELECT          A.*,
                B.NUMBER3
FROM
(
SELECT DISTINCT [NAME]                              , 
                MAX([ARCHIVEDT]) AS [ARCHIVEDT]     ,
                NUMBER1                             ,
                NUMBER2
FROM            [SAEI].[DBO].[ARCHIVEMESSAGES_ACARS]
WHERE           ARCHIVEDT>=DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()-1), 0) 
AND             ARCHIVEDT<DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
AND             [NAME] IS NOT NULL
GROUP BY        [NAME] ,
                [NUMBER1],
                [NUMBER2]
)   AS A
 INNER JOIN     [SAEI].[DBO].[ARCHIVEMESSAGES_ACARS] AS B ON B.[NAME] = A.
[NAME]