SQL Server : multiple rows single line

gfttwv5a  于 2023-03-17  发布在  SQL Server
关注(0)|答案(2)|浏览(179)

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

IDSCHOOLAUT
111A
211A
212B
311A
412A
413B
513A

TABLE-3

IDTC
1101
2102
2103
2104
3105
4106
4107
5108

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
IDSCHOOLTCAUT
111101A
211102A
212102B
211103A
212103B
211104A
212104B
311105A
412106A
413106B
412107A
413107B
513106A

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.

i7uq4tfw

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:

with t as (
    select t2.id,t2.school,t3.tc, Row_Number() over(partition by t2.id order by t3.tc) col
    from t2 join t3 on t2.id=t3.id
    where aut='A'
)
select id,school,
    max(case when col=1 then tc end) TC1,
    max(case when col=2 then tc end) TC2,
    max(case when col=3 then tc end) TC3
from t
group by id, school

Example SQL Fiddle

9wbgstp7

9wbgstp72#

SELECT 
    T1.ID, T2.SCHOOL, 
    GROUP_CONCAT(T3.TC), 
    GROUP_CONCAT(T2.AUT) 
FROM 
    T1 
LEFT OUTER JOIN 
    T2 ON T1.ID = T2.ID 
LEFT OUTER JOIN 
    T3 ON T1.ID = T3.ID 
GROUP BY 
    T1.ID, T2.SCHOOL 
WHERE 
    T2.AUT = ‘A’ 
ORDER BY 
    T1.ID ASC

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 with STRING_AGG if you’re using SQL Server 2017 or newer.

相关问题