用途:
SELECT x.*
FROM (SELECT s.*,
ROW_NUMBER() OVER(PARTITION BY s.fk
ORDER BY s.pk) rnk
FROM YOUR_TABLE s) x
WHERE x.rnk = 1
...或使用CTE(沒有性能上的差異):
WITH example AS (
SELECT s.*,
ROW_NUMBER() OVER(PARTITION BY s.fk
ORDER BY s.pk) rnk
FROM sample s)
SELECT x.*
FROM example x
WHERE x.rnk = 1
證明:
WITH sample AS (
SELECT 1 AS PK, 11 AS FK, 'A' AS [TYPE]
UNION ALL
SELECT 2 AS PK, 11 AS FK, 'B' AS [TYPE]
UNION ALL
SELECT 3 AS PK, 12 AS FK, 'B' AS [TYPE]
UNION ALL
SELECT 4 AS PK, 13 AS FK, 'C' AS [TYPE]
UNION ALL
SELECT 5 AS PK, 13 AS FK, 'D' AS [TYPE]
UNION ALL
SELECT 6 AS PK, 14 AS FK, 'D' AS [TYPE])
SELECT x.*
FROM (SELECT s.*, ROW_NUMBER() OVER(PARTITION BY s.fk
ORDER BY s.pk) rnk
FROM sample s) x
WHERE x.rnk = 1
結果:
pk fk type
----------------
1 11 A
3 12 B
4 13 C
6 14 D
TSQL如在Sybase或SQL Server? –
所以你不清楚,你的意思是說,如果它的值爲W,那麼只能濾除X,Y和Z?這是否意味着允許在A-V?但是,如果存在這些較低值中的任何一個,那麼這是否也意味着你濾除了低於該較低值的一切?這將等於讓所有的值都等於存在的字母表中的最低字母,並且沒有其他值... –
我正在使用SQL Server。在我看來,這些值有優先權,所以如果有一個A,那麼就返回那個,否則如果有一個B,就返回那個,等等。每個FK值只返回一行,那個具有最高優先級的行類型值。 – swandog