gpt4 book ai didi

sql - 如何在 SQL Server 中为分组依据中的 max(column) 的另一列选择等效行

转载 作者:行者123 更新时间:2023-12-04 22:20:21 24 4
gpt4 key购买 nike

我需要在下面的 Sql 中进行更改,使 CreatedOn 返回所选的 Max(Value) 记录。您可以观察 -- todo 行

Should return: 2/01/2015 and 8/01/2015 as you can see in Query Result, but the Max(CreatedOn) will select the max and not the referent record of the Max(Value).

SQL

SET DATEFIRST 1
SELECT
CONCAT(DATEPART(YEAR, CreatedOn),DATEPART(WEEK, CreatedOn)) Week,
MAX(CreatedOn) CreatedOn, -- todo: this should return 2/01/2015 and 8/01/2015
MAX(Value) AS MaxValue
FROM Table1
GROUP BY CONCAT(DATEPART(YEAR, CreatedOn),DATEPART(WEEK, CreatedOn))

表 1:

╔════╦═══════════╦═══════╗
║ Id ║ CreatedOn ║ Value ║
╠════╬═══════════╬═══════╣
║ 1 ║ 1/01/2015 ║ 1 ║
║ 2 ║ 2/01/2015 ║ 2 ║
║ 3 ║ 8/01/2015 ║ 4 ║
║ 4 ║ 9/01/2015 ║ 2 ║
╚════╩═══════════╩═══════╝

查询结果:

╔════════╦═══════════╦══════════╗
║ Week ║ CreatedOn ║ MaxValue ║
╠════════╬═══════════╬══════════╣
║ 2015 1 ║ 2/01/2015 ║ 2 ║
║ 2015 2 ║ 8/01/2015 ║ 4 ║
╚════════╩═══════════╩══════════╝

*Edited: I need to return 8/01/2015 because it is the correspondent row of the MaxValue (4).

最佳答案

您可以在每周的分区上使用 ROW_NUMBER()(PARTITION BY Week),按降序值排序(ORDER BY Value DESC) 对一周内的每条记录进行“排名”。每周选择具有最高值的行就是每个分区中排名最高的行(WHERE Rnk = 1)。我使用 CTE 来防止重复周计算。

WITH Weeks AS
(
SELECT CONCAT(DATEPART(YEAR, CreatedOn),DATEPART(WEEK, CreatedOn)) Week,
Id, CreatedOn, Value
FROM Table1
),
Ranked As
(
SELECT Week, CreatedOn, Value,
ROW_NUMBER() OVER (PARTITION BY Week ORDER BY Value DESC) Rnk
FROM Weeks
)
SELECT Week, CreatedOn, Value
FROM Ranked
WHERE Rnk = 1;

SqlFiddle here

关于sql - 如何在 SQL Server 中为分组依据中的 max(column) 的另一列选择等效行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30318019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com