简体   繁体   中英

SQL Query: Get rows (all columns) from table basied on one distinct column

this is a sample data to explain my case:

替代文字

I want to get data distinct by EMPLOYID , so only 5199, 6000, 6100 employees returned, and for the rest of columns what ever data returned it would be OK

My try: I planned to get distinct EMPLOYID first then get top 1 for each Employee but it seems need a loop, and in my case i restricted to only select query.

Assuming SQL Server 2005 or later, here's a basic example to demonstrate one approach:

DECLARE @Data TABLE (ID INTEGER, NameField VARCHAR(10))
INSERT @Data VALUES (1, 'A')
INSERT @Data VALUES (1, 'B')
INSERT @Data VALUES (1, 'C')
INSERT @Data VALUES (2, 'A')
INSERT @Data VALUES (3, 'C')
INSERT @Data VALUES (3, 'B')

SELECT ID, NameField FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS RowNo, *
FROM @Data
) x
WHERE RowNo = 1

Here's the reference on ROW_NUMBER

尝试SELECT * FROM myTable GROUP BY EMPLOYID

I haven't tested it but I think this should do the trick:

declare @DISTINCTEMPLOYIDS table
    (IDS  char(8)) --whatever datatype employid is

insert into @DISTINCTEMPLOYIDS (IDS)
select distinct EMPLOYID
from TABLENAME

select *
from TABLENAME as t
join @@DISTINCTEMPLOYIDS as d
on t.EMPLOYID = d.EMPLOYID

Remember to change TABLENAME to whatever the name of your table is

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