I am having a hard time doing the following:
select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
inner join (select distinct LastName from
ValTbl v where a.LastName = v.LastName)
I want to do a join on ValTbl but only for distinct values.
5条答案
按热度按时间qxsslcnc1#
I think you actually provided a good start for the correct answer right in your question (you just need the correct syntax). I had this exact same problem, and putting DISTINCT in a sub-query was indeed less costly than what other answers here have proposed.
7z5jn7bk2#
UPDATE (2023): Denis M. Kitchen's answer can be better than my answer from a performance point of view, but it's important to mention that his query can produce a different result than mine, if the same
(FirstName, LastName)
combination appears in more than 1 record inAddTbl
(see the example here ). This can be either good or bad, depending on the particular use case.MY ORIGINAL ANSWER (2011):
Try this:
Or this (it does the same, but the syntax is different):
3vpjnl9f3#
You can use CTE to get the distinct values of the second table, and then join that with the first table. You also need to get the distinct values based on LastName column. You do this with a Row_Number() partitioned by the LastName, and sorted by the FirstName.
Here's the code
nhjlsmyf4#
add "distinct" after "select".
p8ekf7hl5#
It's not the same doing a select distinct at the beginning because you are wasting all the calculated rows from the result.
try that.