T-SQL ORDER BY基于组列的MIN

时间:2014-04-28 05:54:32

标签: sql sql-server-2008-r2

您可以将以下数据作为示例

id | value
----------
 A |   3
 A |   9
 B |   7
 B |   2
 C |   4
 C |   5

我想列出每个id组的最小值的所有数据,以便预期输出为

id | value
----------
 B |   2
 B |   7
 A |   3
 A |   9
 C |   4
 C |   5

即。 A组的最小值为3,B组为2,C组为4,因此B组先行,B组的其余部分按升序排列。接下来是A组,然后是C组

我试过了,但这不是我想要的

SELECT * FROM (
SELECT 'A' AS id, '3' AS value
UNION SELECT 'A', '9' UNION SELECT 'B', '7' UNION SELECT 'B', '2'
UNION SELECT 'C', '4' UNION SELECT 'C', '5') data
GROUP BY id, value
ORDER BY MIN(value)

请帮忙!谢谢

1 个答案:

答案 0 :(得分:3)

SELECT * FROM (
SELECT 'A' AS id, '3' AS value
UNION SELECT 'A', '9' UNION SELECT 'B', '7' UNION SELECT 'B', '2'
UNION SELECT 'C', '4' UNION SELECT 'C', '5') data
ORDER BY MIN(value) OVER(PARTITION BY id), id, value

OVER Clause (Transact-SQL)

将over()子句添加到查询输出中,您可以看到它为您做了什么。

SELECT *, 
       MIN(value) OVER(PARTITION BY id) OrderedBy FROM (
SELECT 'A' AS id, '3' AS value
UNION SELECT 'A', '9' UNION SELECT 'B', '7' UNION SELECT 'B', '2'
UNION SELECT 'C', '4' UNION SELECT 'C', '5') data
ORDER BY MIN(value) OVER(PARTITION BY id), id, value

结果:

id   value OrderedBy
---- ----- ---------
B    2     2
B    7     2
A    3     3
A    9     3
C    4     4
C    5     4