gpt4 book ai didi

sql - 按列顺序获取相同的范围值

转载 作者:行者123 更新时间:2023-12-02 09:29:37 24 4
gpt4 key购买 nike

我有一张 table

ID Value
1 2
2 3
3 3
4 3
5 2
6 2
7 1

我想对值进行分组,但仍然按 ID 排序,如下所示

ID   Value
1 2
2-4 3
5-6 2
7 1

我该怎么做?

最佳答案

DECLARE @t TABLE (
ID INT PRIMARY KEY,
Value INT
)

INSERT INTO @t (ID, Value)
VALUES (1,2),(2,3),(3,3),(4,3),(5,2),(6,2),(7,1)

SELECT
ID =
CASE WHEN mx = mn
THEN CAST(mx AS VARCHAR(10))
ELSE CAST(mn AS VARCHAR(10)) + '-' + CAST(mx AS VARCHAR(10))
END,
Value
FROM (
SELECT group_id, mx = MAX(ID), mn = MIN(ID), Value = MAX(Value)
FROM (
SELECT
*
, group_id =
ROW_NUMBER() OVER (ORDER BY ID) -
ROW_NUMBER() OVER (PARTITION BY Value ORDER BY ID)
FROM @t
) t
GROUP BY group_id
) t

输出 -

ID    Value
----- -----------
1 2
2-4 3
5-6 2
7 1

关于sql - 按列顺序获取相同的范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34508527/

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