简体   繁体   中英

SQL select first records of rows for specific column

I realize my title probably doesnt explain my situation very well, but I honestly have no idea how to word this.

I am using SQL to access a DB2 database.

Using my screenshot image 1 below as a reference:

column 1 has three instances of "U11124", with three different descriptions (column 2)

I would like this query to return the first instance of "U11124" and its description, but then also unique records for the other rows. image 2 shows my desired result.

image 1

此搜索

image 2

图像2

----- EDIT ----

to answer some of the questions / posts: technically, it does not need to be the first , just any single one of those records. the problem is that we have three descriptions, and only one needs to be shown, i am now told it does not matter which one.

SELECT STVNST, MAX(STDESC) FROM MY_TABLE GROUP BY STVNST;

In SQL Server:

select stvnst, stdesc
from (
  select     
     stvnst, stdesc
     row_number() over (order by stdesc partition by stvnst) row
  from table
) a
where row = 1

This method has an advantage over a simple group by, in that it will also work when there's more than two columns in the table.

SELECT STVNST,FIRST(STDESC) from table group by STVNST ORDER BY table_ SELECT STVNST,FIRST(STDESC) from table group by STVNST what_you_want_first

All you need to do is use GROUP BY.

You say you want the first instance of the STDESC column? Well you can't guarntee the order of the rows without another column, however if you want to order by the highest ordered value the following will suffice:

SELECT STVNST, MAX(STDESC) FROM MY_TABLE GROUP BY STVNST;

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