简体   繁体   中英

SQL Server Select Group by can't group

I have this table:

ID  TXT VL 
----------
1   A   1
2   B   0
4   C   0
6   D   0
10  D   0
13  E   0
14  C   0
15  E   0

I have no idea how I can select only the first appearance of TXT like this:

ID  TXT VL 
----------
1   A   1
2   B   0
4   C   0
6   D   0
13  E   0

You can do the following:

select t1.* 
from tbl t1 
join (select min(id) as id from tbl group by txt) t2 on t1.id = t2.id

In the temporary table you find all first occurrences of each uniq txt and then join it with the original table.

You can do it with ROW_NUMBER() OVER , like this:

WITH CTE AS (
      SELECT *
           , ROW_NUMBER() OVER (PARTITION BY TXT ORDER BY ID) AS RowN
      FROM table
)
SELECT ID, TXT, VL
FROM CTE
WHERE RowN = 1

Hope it helps :)

For more reading: https://msdn.microsoft.com/en-us/library/ms189461.aspx And https://msdn.microsoft.com/en-us/library/ms186734.aspx

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