简体   繁体   中英

SELECT MAX() of Column, DATE Column and group by ID

I would like to select the MAX() Facility Level Status from a table per AssetId, but also get the associated date.

I can get the max level per assetID, but can't figure out how to bring the associated date since I am grouping by AssetID, but the date is unique.

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

I expect the output to be the following:

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

With NOT EXISTS:

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

See the demo .
Results:

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

You can use a correlated subquery:

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

You can write a query using MAX ([ ALL ] expression) OVER ( [ <partition_by_clause> ] [ <order_by_clause> ] ) as :

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM