I would like to get the representation of one record based on the primary key value from multiple tables. As shown below, each table can have multiple values based on this primary key value.
TABLE-1
| ID | NAME |
| ------------ | ------------ |
| 1 | AA |
| 2 | BB |
| 3 | CC |
| 4 | DD |
| 5 | EE |
TABLE-2
ID | SCHOOL | AUT |
---|---|---|
1 | 11 | A |
2 | 11 | A |
2 | 12 | B |
3 | 11 | A |
4 | 12 | A |
4 | 13 | B |
5 | 13 | A |
TABLE-3
ID | TC |
---|---|
1 | 101 |
2 | 102 |
2 | 103 |
2 | 104 |
3 | 105 |
4 | 106 |
4 | 107 |
5 | 108 |
The result below is the value obtained with an OUTER JOIN
.
SELECT
T1.ID, T2.SCHOOL, T3.TC, T2.AUT
FROM
T1
LEFT OUTER JOIN
T2 ON T1.ID = T2.ID
LEFT OUTER JOIN
T3 ON T1.ID = T3.ID
ORDER BY
T1.ID ASC
ID | SCHOOL | TC | AUT |
---|---|---|---|
1 | 11 | 101 | A |
2 | 11 | 102 | A |
2 | 12 | 102 | B |
2 | 11 | 103 | A |
2 | 12 | 103 | B |
2 | 11 | 104 | A |
2 | 12 | 104 | B |
3 | 11 | 105 | A |
4 | 12 | 106 | A |
4 | 13 | 106 | B |
4 | 12 | 107 | A |
4 | 13 | 107 | B |
5 | 13 | 106 | A |
How can I get the result like below?
| ID | SCHOOL | TC1 | TC2 | TC3 |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | 11 | 101 | | |
| 2 | 11 | 102 | 103 | 104 |
| 3 | 11 | 105 | | |
| 4 | 12 | 106 | 107 | |
| 5 | 13 | 108 | | |
The important thing here is that in the result value, SCHOOL only shows that AUT is 'A'.
I would appreciate it if you let me know your query.
2条答案
按热度按时间i7uq4tfw1#
It looks, from your desired results, you just need to use
row_number
in combination with a conditional aggregate. Your sample data seems a little inadequate, I can't see any requirement for table1 at all.Try the following:
Example SQL Fiddle
9wbgstp72#
Notice that GROUP_CONCAT concatenates the values in the row.
EDIT: oh my, haven't seen that it's a SQL Server question!
Just replace
GROUP_CONCAT
withSTRING_AGG
if you’re using SQL Server 2017 or newer.