如何选择每组的顶部和底部记录?

时间:2009-04-07 11:27:00

标签: sql sql-server-2008

说,我在数据库(SQL Server 2008)中有一个表,其数据与此类似  (但更多,更大):

| ID | SCORE | GROUP |
-----------------------
| 10 |     1 | A     |
| 6  |     2 | A     |
| 3  |     3 | A     |
|----|-------|-------|
| 8  |     5 | B     |
|----|-------|-------|
| 4  |     1 | C     |
| 9  |     3 | C     |
| 2  |     4 | C     |
| 7  |     4 | C     |
|----|-------|-------|
| 12 |     3 | D     |
| 1  |     3 | D     |
| 11 |     4 | D     |
| 5  |     6 | D     |

我想获取每个ID的顶部和底部记录的GROUP,其中每个组的记录按SCORE排序(并补充地,{{1} }}),像这样:

ID

问题是:我怎样才能做到这一点?

到目前为止,我一直在尝试基于| GROUP | MIN_ID | MAX_ID | ---------------------------- | A | 10 | 3 | | B | 8 | 8 | | C | 4 | 7 | | D | 1 | 5 | 函数的解决方案,但是没有管理查找一个既产生正确输出又模糊效率或可维护的查询。


注意:

简化了这个例子。我的'table'实际上是一个已经很复杂的查询的输出,我正在寻找最后阶段。我宁愿只从表中选择一次。

如果可能的话,最好有一个通用解决方案,允许我选择每组的顶部和底部RANK()值。

n的顺序不合适。

4 个答案:

答案 0 :(得分:5)

  

如果可能的话,最好有一个通用解决方案,允许我选择每组的顶部和底部n值。

WITH q AS
        (
        SELECT  m.*,
                ROW_NUMBER() OVER (PARTITION BY Group ORDER BY Score) AS rn_asc,
                ROW_NUMBER() OVER (PARTITION BY Group ORDER BY Score DESC) AS rn_desc
        FROM    mytable m
        )
SELECT  *
FROM    q
WHERE   rn_asc BETWEEN 1 AND 10
        OR rn_desc BETWEEN 1 AND 10

答案 1 :(得分:3)

DECLARE @YourTable TABLE (ID INTEGER, Score INTEGER, [Group] VARCHAR(1))
INSERT INTO @YourTable VALUES (10, 1, 'A')
INSERT INTO @YourTable VALUES (6 , 2, 'A')
INSERT INTO @YourTable VALUES (3 , 3, 'A')
INSERT INTO @YourTable VALUES (8 , 5, 'B')
INSERT INTO @YourTable VALUES (4 , 1, 'C')
INSERT INTO @YourTable VALUES (9 , 3, 'C')
INSERT INTO @YourTable VALUES (2 , 4, 'C')
INSERT INTO @YourTable VALUES (7 , 4, 'C')
INSERT INTO @YourTable VALUES (12, 3, 'D')
INSERT INTO @YourTable VALUES (1 , 3, 'D')
INSERT INTO @YourTable VALUES (11, 4, 'D')
INSERT INTO @YourTable VALUES (5 , 6, 'D')  

SELECT [Group], MIN([Min_ID]), MAX([Max_ID])
FROM (
  SELECT [score].[Group], [Min_ID] = [min].ID, [Max_ID] = [max].ID
  FROM (
    SELECT [Group], [Min_Score] = MIN(Score), [Max_Score] = MAX(Score)
    FROM @YourTable
    GROUP BY [GROUP]) score
    INNER JOIN @YourTable [min] ON [min].[Group] = [score].[Group] AND [min].[Score] = [score].[Min_Score]
    INNER JOIN @YourTable [max] ON [max].[Group] = [score].[Group] AND [max].[Score] = [score].[Max_Score] 
  ) yourtable
GROUP BY [yourtable].[Group]

答案 2 :(得分:1)

任何解决方案都需要在组和分数上有一些好的索引,但包括ID

SELECT
    foo.[Group],
    m1.ID AS Min_ID,
    m2.ID AS Max_ID
FROM
    (
    SELECT
       [Group], MIN(Score) AS MinScore, MAX(Score) AS MaxScore
    FROM
       mytable
    GROUP BY
       [Group]
    ) foo
    JOIN
    mytable m1 ON foo.[Group] = m1.[Group] AND foo.MinScore = m1.Score
    JOIN
    mytable m2 ON foo.[Group] = m2.[Group] AND foo.MaxScore = m2.Score

然而,在您的示例数据中,这也有效,因为ID和分数按顺序对齐:

SELECT
    [Group],
    MIN(ID) AS Min_ID,
    MAX(ID) AS Max_ID
FROM
    mytable
GROUP BY
    [Group]

答案 3 :(得分:0)

您可以使用子查询(SELECT TOP 1)...