mweis
mweis

Reputation: 37

How can I use distinct only for certain table variables?

I am trying to use 'distinct' on all Home(table name) variables however i am also selecting other variables from other tables too. How can i only choose distinct select for Home variables/or only certain columns?

This query is using distinct for ALL variables including the ones for anotherTable.

Here is my query

 SELECT distinct f.q_id, f.var2, f.var3, f.var4, m.var22
 FROM Home f, anotherTable m
 WHERE f.q_id = m.q_id 

I tried wrapping variables individually with distinct but that will not allow me to make my distinct preference on variables.

Upvotes: 0

Views: 49

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270463

One method uses group by:

SELECT f.q_id, f.var2, f.var3, f.var4, MAX(m.var22)
FROM Home f JOIN
     anotherTable m
     ON f.q_id = m.q_id 
GROUP BY f.q_id, f.var2, f.var3, f.var4;

Upvotes: 0

Shushil Bohara
Shushil Bohara

Reputation: 5656

Try this, to select DISTINCT data only from Home and ALL from anotherTable:

SELECT t.q_id, t.var2, t.var3, t.var4, m.var22
FROM anotherTable m
INNER JOIN (SELECT DISTINCT 
             f.q_id, f.var2, f.var3, f.var4 FROM Home f) t ON t.q_id = m.q_id

Upvotes: 1

Related Questions