SELECT MAX()的列,DATE列和按ID分组

时间:2019-09-18 18:54:15

标签: sql group-by sql-server-2012 max

我想从每个AssetId的表中选择MAX()设施级别状态,但还要获取关联的日期。

我可以获取每个assetID的最高级别,但是由于我是按AssetID分组的,因此无法弄清楚如何携带关联的日期,但是该日期是唯一的。

DROP TABLE #temp

CREATE TABLE #temp 
(AssetId int, FacilityStatusLevel int, DateProcessed date)

INSERT INTO #temp(AssetId, FacilityStatusLevel, DateProcessed)
VALUES
(1, 1,'2019-01-01'), 
(1, 2,'2019-01-02'),
(2, 3,'2019-01-03'),
(2, 4,'2019-01-04'),
(3, 5,'2019-01-05')


SELECT  AssetID, MAX(#temp.FacilityStatusLevel) as MaxFacilityStatusLevel
FROM #temp
GROUP BY AssetID

我希望输出如下:

AssetID |   MaxFacilityStatusLevel | DateProcessed
  1           2                        2019-01-02
  2           4                        2019-01-04
  3           5                        2019-01-05

3 个答案:

答案 0 :(得分:1)

不存在:

SELECT t.* FROM #temp t
WHERE NOT EXISTS (
  SELECT 1 FROM #temp
  WHERE AssetID = t.AssetID AND FacilityStatusLevel > t.FacilityStatusLevel
)

请参见demo
结果:

AssetId | FacilityStatusLevel | DateProcessed      
------: | ------------------: | :------------
      1 |                   2 | 02/01/2019
      2 |                   4 | 04/01/2019
      3 |                   5 | 05/01/2019

答案 1 :(得分:0)

您可以使用相关子查询:

select t.*
from #temp t
where t.FacilityStatusLevel = (select max(t2.FacilityStatusLevel) from #temp t2 where t2.assetid = t.assetid);

答案 2 :(得分:0)

您可以使用MAX ([ ALL ] expression) OVER ( [ <partition_by_clause> ] [ <order_by_clause> ] )来编写查询:

Select 
       AssetId, 
       MaxFacilityStatusLevel,
       DateProcessed
from 
(
select AssetId , 
       max(FacilityStatusLevel) over (partition by AssetId ) as
       MaxFacilityStatusLevel,
       row_number() over (partition by AssetId order by FacilityStatusLevel desc ) as 
       rownum,
       DateProcessed
from #temp 
) T 
where T.rownum = 1

Sample code here...