gpt4 book ai didi

tsql - t-sql 按类别分组并获取前 n 个值

转载 作者:行者123 更新时间:2023-12-04 22:51:18 25 4
gpt4 key购买 nike

想象一下我有这张 table :

Month | Person | Value
----------------------
Jan | P1 | 1
Jan | P2 | 2
Jan | P3 | 3
Feb | P1 | 5
Feb | P2 | 4
Feb | P3 | 3
Feb | P4 | 2
...

如何构建 t-sql 查询以获取前 2 个值行和第三个值行的总和?

像这样的东西:
RESULT: 
Month | Person | Value
----------------------
Jan | P3 | 3
Jan | P2 | 2
Jan | Others | 1 -(sum of the bottom value - in this case (Jan, P1, 1))
Feb | P1 | 5
Feb | P2 | 4
Feb | Others | 5 -(sum of the bottom values - in this case (Feb, P3, 3) and (Feb, P4, 2))

谢谢

最佳答案

假设您使用的是 SQL Server 2005 或更高版本,则使用 CTE 即可解决问题。

  • 附上 ROW_NUMBER到每一行,从最高值开始,每个月重置。
  • SELECT此查询中每个月的前 2 行 (rownumber <= 2)
  • UNION剩余的行(行号 > 2)

  • SQL 语句
    ;WITH Months (Month, Person, Value) AS (
    SELECT 'Jan', 'P1', 1 UNION ALL
    SELECT 'Jan', 'P2', 2 UNION ALL
    SELECT 'Jan', 'P3', 3 UNION ALL
    SELECT 'Feb', 'P1', 5 UNION ALL
    SELECT 'Feb', 'P2', 4 UNION ALL
    SELECT 'Feb', 'P3', 3 UNION ALL
    SELECT 'Feb', 'P4', 2
    ),
    q AS (
    SELECT Month
    , Person
    , Value
    , RowNumber = ROW_NUMBER() OVER (PARTITION BY Month ORDER BY Value DESC)
    FROM Months
    )
    SELECT Month
    , Person
    , Value
    FROM (
    SELECT Month
    , Person
    , Value
    , RowNumber
    FROM q
    WHERE RowNumber <= 2
    UNION ALL
    SELECT Month
    , Person = 'Others'
    , SUM(Value)
    , MAX(RowNumber)
    FROM q
    WHERE RowNumber > 2
    GROUP BY
    Month
    ) q
    ORDER BY
    Month DESC
    , RowNumber

    Kudo 去找 Andriy 教我一些新技巧。

    关于tsql - t-sql 按类别分组并获取前 n 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091747/

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