WHERE ID = MAX(ID)可能不会出现错误聚合

时间:2014-01-14 12:13:09

标签: sql sql-server tsql

我遇到了一个问题,我已经放在一起了,我已经按照http://www.sql-server-helper.com/error-messages/msg-147.aspx(页面底部)的说明进行操作了,我看不出我的代码与示例有什么不同除了WHERE子句和内部联接。

但我仍然收到以下错误:

  

Msg 147,Level 15,State 1,Line 5
  聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。

这是我自己的代码:

SELECT  *
FROM    [dbo].[mail] AS rm
    INNER JOIN [dbo].[mytbl] AS ec ON [rm].[webref] = [ec].[Webref]
WHERE   rm.[webref] = 'XYZ-594112'
    AND [PolRef@] = ( SELECT    MAX([PolRef@])
                      FROM      [dbo].[mytbl]
                    )

任何人都可以解释为什么会发生这种情况吗?

编辑:

CREATE TABLE [dbo].[mail](
[id] [int] IDENTITY(1,1) NOT NULL,
[date] [datetime] NULL,
[webref] [nvarchar](20) NULL
) ON [PRIMARY]  

另一个表实际上是一个由几个其他表组成的视图,但是减少的版本将是:

CREATE TABLE [dbo].[mytbl](
[PolRef@] [varchar](10) NULL,
[Webref] [varchar](30) NULL) ON [PRIMARY]

编辑更新:

现在收到以下错误:

SELECT  *
FROM    [FreshSystems].[dbo].[mail] AS rm
    INNER JOIN [dbo].[mytbl] AS ec ON [rm].[webref] = [ec].[Webref]
WHERE   rm.[webref] = 'XYZ-594112'
HAVING [PolRef@] = ( SELECT    MAX([PolRef@])
                      FROM      [dbo].[mytbl]
                    )

错误

Msg 8121, Level 16, State 1, Line 5
Column 'mytbl.PolRef@' is invalid in the HAVING clause because it is not     contained in either an aggregate function or the GROUP BY clause.

WORKING:

SELECT  *
FROM    [dbo].[mail] AS rm
LEFT OUTER JOIN  [dbo].[mytbl] AS ec ON [rm].[webref] = [ec].[Webref]
WHERE   rm.[webref] = 'XYZ-594112'
AND [PolRef@] = ( SELECT    MAX([PolRef@])
                  FROM      [dbo].[mytbl]
                  WHERE [Webref] = 'XYZ-594112'
                )

3 个答案:

答案 0 :(得分:1)

我会用这样的东西

select  *
from    [dbo].[mail] as rm
join    [dbo].[mytbl] as ec
on      [rm].[webref] = [ec].[webref]
join    ( select    max([polref@]) y
          from      [dbo].[mail]
        ) x
on      [polref@] = x.y
where   rm.[webref] = 'xyz-594112'

答案 1 :(得分:1)

只需按poltef@ desc排序,然后选择前1:

SELECT TOP 1 * WITH TIES
FROM mail rm
JOIN mytbl ec ON rm.webref = ec.Webref
WHERE rm.webref = 'XYZ-594112'
ORDER BY poltef@ desc

另外,我删除了所有不必要的字符。

答案 2 :(得分:0)

工作代码:

SELECT  *
FROM    [dbo].[mail] AS rm
LEFT OUTER JOIN  [dbo].[mytbl] AS ec ON [rm].[webref] = [ec].[Webref]
WHERE   rm.[webref] = 'XYZ-594112'
AND [PolRef@] = ( SELECT    MAX([PolRef@])
                  FROM      [dbo].[mytbl]
                  WHERE [Webref] = 'XYZ-594112'
                )