wheaties
wheaties

Reputation: 35980

SQL: Sort a table by the first relation to a second table

I have a Many-to-Many relationship between two tables. I'd like to sort the first table by the first relationship with the second table and only return a single result from that table. This is on SQL Server. I'd like something like this:

SELECT a.retrieve_me
FROM table_A AS a
JOIN table_B AS b ON a.foo = b.foo
JOIN table_C AS c ON b.bar = c.bar
ORDER BY c.sort_me

Unfortunately it returns MN(k) results, where M is the count of "table_A" and N(k) is the number of relations of a single row k with "table_C." To have it return just the results I wanted without post filtering I tried using DISTINCT on the SELECT clause and using TOP(SELECT COUNT(*) FROM table_A) but neither are valid syntax.

Any ideas? Hoping I can make this as performant as possible.

EDIT:

For clarity

table A
------------
"joe" 1
"betty" 2
"george" 3

table B
------------
1 2
1 3
2 3
2 4
3 1

table C
------------
1 "ashton"
2 "harding"
3 "spring"
4 "merry lane"

I'd like the results returned in the order of "george", "joe", and "betty" which is in the order (george -> ashton, joe -> harding, betty -> merry lane.)

Upvotes: 0

Views: 118

Answers (1)

Dumitrescu Bogdan
Dumitrescu Bogdan

Reputation: 7267

If I understood correctly what you need, cause I think is very hard to follow you .. this should do it:

SELECT a.nm
FROM tablea a
cross apply (select top 1 * 
         from tableb b
         join tablec c on b.id2 = c.id
         where a.id = b.id1
         order by c.nm) bc
order by bc.nm

http://sqlfiddle.com/#!3/661c0/5/0

Upvotes: 3

Related Questions