简体   繁体   中英

Retrieve the first result for each field on sql table

I have a sql table like this:

code label
1 row
1 row2
2 row3
2 row4
2 row5

I want to retrieve the first description for each 'code' For ex:

code label
1 row
2 row3

How can be the SQL query?

There is an ability to enumerated rows within each code with order by label .

/*
WITH MYTABLE (code, label) AS
(
VALUES
  (1, 'row')
, (1, 'row2')
, (2, 'row3')
, (2, 'row4')
, (2, 'row5')
)
*/
SELECT CODE, LABEL
FROM
(
  SELECT ROW_NUMBER () OVER (PARTITION BY CODE ORDER BY LABEL) AS RN_
, T.*
FROM MYTABLE T  
) 
WHERE RN_ = 1
CODE LABEL
1 row
2 row3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM