SQL

时间:2017-02-28 03:57:55

标签: sql sql-server sql-server-2008

我有下表要按类型分组。当存在多个具有相同类型的行(例如,A& B类型)时,我想保留具有最高等级的行中的“值”(即,主要>辅助>三级...)

rowid | type  | rank       | value
    1 | A     | primary    |  1
    2 | A     | secondary  |  2

    3 | B     | secondary  |  3
    4 | B     | tertiary   |  4

    5 | C     | primary    |  5

因此生成的表应该看起来像

rowid | type | rank      | value
    1 | A    | primary   | 1
    3 | B    | secondary | 3
    5 | C    | primary   | 5

任何建议都将受到高度赞赏!

p.s。,我在MS SQL Server中工作。

3 个答案:

答案 0 :(得分:4)

您可以使用select t.* from (select t.*, row_number() over (partition by type order by charindex(rank, 'primary,secondary,tertiary') ) as seqnum from t ) t where seqnum = 1; 。这是一个简单的方法:

charindex()

这使用 .copyright-container { margin: 0 auto; position: ralative; text-align: center; padding: 0px; } 作为排序等级的简单方法。

答案 1 :(得分:1)

试试这个,

;WITH CTE
AS (
    SELECT *
        ,row_number() OVER (
            PARTITION BY [type] ORDER BY value
            ) rn
    FROM @t
    )
SELECT *
FROM cte
WHERE rn = 1

答案 2 :(得分:1)

另一种方法是使用Row_NumberOrder By使用CASE指定您的规则。

<强>架构:

CREATE TABLE #TAB(rowid  INT, [type] VARCHAR(1), rankS VARCHAR(50)   ,      value INT)
INSERT INTO #TAB
SELECT 1 , 'A' , 'primary' , 1
UNION ALL
SELECT 2 , 'A' , 'secondary', 2
UNION ALL
SELECT 3 , 'B' , 'secondary' , 3
UNION ALL
SELECT 4 , 'B' , 'tertiary' , 4
UNION ALL
SELECT 5 , 'C' , 'primary' , 5

现在使用Row_Number

应用排名规则
SELECT * FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY [type] ORDER BY (CASE rankS
WHEN 'primary' THEN 1
WHEN 'secondary' THEN 2
WHEN 'tertiary' THEN 3 END )) AS SNO, * FROM #TAB
)A
WHERE SNO =1

结果:

+-----+-------+------+-----------+-------+
| SNO | rowid | type |   rankS   | value |
+-----+-------+------+-----------+-------+
|   1 |     1 | A    | primary   |     1 |
|   1 |     3 | B    | secondary |     3 |
|   1 |     5 | C    | primary   |     5 |
+-----+-------+------+-----------+-------+