[英]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. 我想从每个AssetId的表格中选择MAX()设施等级状态,但也要获取关联的日期。
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. 我可以获取每个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
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 : 您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.