SQL Query Returns different results based on the number of columns selected
Hello I am writing a query and am little confused about the results i'm getting.
select distinct(serial_number) from AssyQC
T开发者_如何学运维his query returns 309,822 results
However if I modify the select statement to include a different column as follows
select distinct(serial_number), SCAN_TIME from AssyQC
The query returns 309,827 results. The more columns I add the more results show up.
I thought the results would be bound to only the distinct serial_number that were returned initially. That is what I want, only the distinct serial_numbers
Can anyone explain this behavior to me?
Thanks
SELECT distinct
applies to the whole selected column list not just serial_number
.
The more columns you add then clearly the more unique combinations you are getting.
Edit
From your comment on Cade's answer
let's say i wanted the largest/latest time stamp
this is what you neeed.
SELECT serial_number, MAX(SCAN_TIME) AS SCAN_TIME
FROM AssyQC
GROUP BY serial_number
Or if you want additional columns
;WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY serial_number
ORDER BY SCAN_TIME DESC) AS RN
FROM AssyQC
)
SELECT *
FROM CTE
WHERE RN=1
you're probably looking for
select distinct on serial_number serial_number, SCAN_TIME from AssyQC
See this related question:
SQL/mysql - Select distinct/UNIQUE but return all columns?
精彩评论