Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT DISTINCT on one column, return multiple other columns (SQL Server)

Tags:

I'm trying to write a query that returns the most recent GPS positions from a GPSReport table for each unique device. There are 50 devices in the table, so I only want 50 rows returned.

Here is what I have so far (not working)

SELECT TOP(SELECT COUNT(DISTINCT device_serial) FROM GPSReport) * FROM GPSReport AS G1
RIGHT JOIN
(SELECT DISTINCT device_serial FROM GPSReport) AS G2
ON G2.device_serial = G1.device_serial
ORDER BY G2.device_serial, G1.datetime DESC

This returns 50 rows, but is not returning a unique row for each device_serial. It returns all of the reports for the first device, then all of the reports for the second device, etc.

Is what I'm trying to do possible in one query?

like image 217
mwalsher Avatar asked Nov 23 '09 20:11

mwalsher


People also ask

Does distinct apply to multiple columns?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.

How do I SELECT distinct one column from multiple columns in SQL?

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.

Can we use distinct on multiple columns in SQL?

Multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.

How do I get unique two column combinations in SQL?

To select distinct combinations from two columns, you can use CASE statement. Let us create a table with some columns.


3 Answers

WITH DEDUPE AS (
    SELECT  *
          , ROW_NUMBER() OVER ( PARTITION BY what_you_want_for_distinct ORDER BY what_you_want_for_distinct) AS OCCURENCE
    FROM tablename
    )
SELECT  * FROM DEDUPE
WHERE
OCCURENCE = 1 
like image 80
Howie Avatar answered Sep 29 '22 09:09

Howie


SELECT * FROM
GPSReport AS G1
JOIN (SELECT device_serial, max(datetime) as mostrecent 
      FROM GPSReport group by device_serial) AS G2
ON G2.device_serial = G1.device_serial and g2.mostrecent = g1.datetime
ORDER BY G1.device_serial
like image 19
Hogan Avatar answered Sep 26 '22 09:09

Hogan


You are having a right join, so if you have more than 1 record for device serial number in table GPSReport, it will get all those record and joint then to the unique list received from SELECT DISTINCT device_serial FROM GPSReport.

like image 2
artdanil Avatar answered Sep 27 '22 09:09

artdanil