I got 2 tables in my db and i want to join them together but because sometime i got more than one record in table 2 that connect to table1 i want to show them in a new column. i have app in .net C# that send the query and read from it.
Table1:
id | name |
---|---|
1 | James |
2 | Jane |
3 | Gil |
Table2:
id | table1_id | countries_visited |
---|---|---|
1 | 1 | USA |
2 | 1 | Germany |
3 | 2 | France |
and i want the end result from the query to be:
id | name | country | country | .... |
---|---|---|---|---|
1 | James | USA | Germany | .... |
2 | Jane | France | no column here | |
3 | Gil | no more columns |
my question is it possible to make rows have different columns? and if its not possible than have all rows max country colums ( changed by the max amount of country visted to single key ) and have null in their value.
ex:
id | name | country | country | .... |
---|---|---|---|---|
1 | James | USA | Germany | .... |
2 | Jane | France | null | .... |
3 | Gil | null | null | .... |
the.... represents if i had more countries to a single key.
maybe i got it all wrong but the reson i want this is because i can have some users with no countries visited and some with one or more without limiting.
You need to pivot on rownumber:
SELECT
id,
name,
MIN(CASE WHEN rn = 1 THEN countries_visited END) country1,
MIN(CASE WHEN rn = 2 THEN countries_visited END) country2,
MIN(CASE WHEN rn = 3 THEN countries_visited END) country3,
......... etc copy paste as many as you need
FROM (
SELECT t1.*, t2.countries_visited,
ROW_NUMBER() OVER (PARTITION BY t1.ID ORDER BY t2.countries_visited) AS rn
FROM Table1 t1
JOIN Table2 t2 ON t2.table1_id = t1.id
) t
GROUP BY id, name;
You can also do this with the PIVOT
keyword, but that is less flexible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.