I have 3 tables that join with together and i want select distinct rows on the B.val3. i use something like this :
SELECT A.val1,A.val2, B.val1, B.val2, B.val3, C.val1, C.val2
FROM A INNER JOIN
B ON A.val1 = B.val1 INNER JOIN
C ON A.val1 = C.val1
this statement get to me 24 rows with duplicate B.val3
now, when i use SELECT DISTINCT A.val1,A.val2, B.val1,..., all 24 records are retrieved, but i want only distinct rows on the B.val3 retrieved (8 rows)
when i use something like :
SELECT DISTINCT A.val1,A.val2, B.val1,
...
C ON A.val1 = C.val1 GROUP BY B.val3
i received an error :
Msg 8120, Level 16, State 1, Line 13
Column 'A.val1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
EDIT : structure and data
table A as follow : val2 is foreign key of B and val3 is foreign key C
val1 val2 val3
----- ----- -----
1 100 200
2 100 201
3 101 200
4 102 200
5 102 201
table B :
val1 val2 val3
----- ----- -----
100 a2 aaa
101 b2 bbb
102 c2 ccc
table C :
val1 val2
----- -----
200 a3
201 b3
and i want get something like :
A.val1 A.val2 A.val3 B.val1 B.val2 B.val3 C.val1 C.val2
----- ----- ----- ----- ----- ----- ----- -----
1 100 200 100 a2 aaa 200 a3
3 101 200 101 b2 bbb 200 a3
4 102 201 102 c2 ccc 201 b3
You could try something like this:
or
Depending on what you’re trying to achieve. If those don’t do what you’re after, please can you provide more info on what you’re hoping to do / example data?
The issue you have is when selecting a distinct b.val3 there may be multiple records associated:
If the answers to either of the above questions are no, you need to give SQL a way to decide which of the multiple possible records/results to select when choosing what data to display for the other columns.
EDIT
Based on example data given above, please find a script to replicate the sample info & display the solution: