【问题标题】:SQL Server Query returning all rows in a table instead of MAX()SQL Server 查询返回表中的所有行而不是 MAX()
【发布时间】:2016-01-31 08:38:16
【问题描述】:

我试图返回库存中每件设备的最高/最后一小时的仪表读数,但是,即使使用 MAX,下面的查询也会列出所有实例。

select      sil.[Posting Date], 
            mre.[Service Item No_], 
            sil.[Job Code], 
            max(mre.[Reading]) as 'Hour Reading'     

from        [$meter reading entry]mre left outer join
            [$service invoice line]sil on mre.[Service Item No_] = sil.[Service Item No_]

where       sil.[Job Code] = 200


group by    mre.[Service Item No_], sil.[Job Code], mre.[Reading], sil.[Posting Date]

【问题讨论】:

  • 您的 sil join 并没有真正做任何事情。当您取出联接并仅使用主表时会发生什么?

标签: tsql sql-server-2005 max


【解决方案1】:

这是因为 mre.[Reading] 也用于 GROUP BY 子句。要获得所需的结果,请从 GROUP BY 中删除 mre.[Reading],然后重试。

select      sil.[Posting Date], 
            mre.[Service Item No_], 
            sil.[Job Code], 
            max(mre.[Reading]) as 'Hour Reading'     

from        [$meter reading entry]mre left outer join
            [$service invoice line]sil on mre.[Service Item No_] = sil.[Service Item No_]

where       sil.[Job Code] = 200


group by    mre.[Service Item No_], sil.[Job Code], sil.[Posting Date]

【讨论】:

  • 优秀。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 2020-11-04
  • 2018-10-28
  • 1970-01-01
  • 2011-01-17
相关资源
最近更新 更多