Home > Net >  SQL Query to merge several views into one
SQL Query to merge several views into one

Time:02-03

I was trying to create a new view out of 3 or 4 other views/tables.

TableA:

title_id homeTeam
1234 WSV
5678 SSV
7890 NULL
4321 SCC

TableB:

title_id awayTeam
1234 SSV
5678 SFV
7890 NULL
4321 KFC

TableC:

title_id homeTeam
1234 SSV
5678 NULL
7890 AAB
4711 BFG

I would like to generate a new view out of those three which looks like:

title_id Teams
1234 WSV, SSV, SSV
5678 SSV, SFV, N/A
7890 N/A, N/A, AAB
4321 SCC, KFC, N/A
4711 N/A, N/A, BFG

As you can see, NULL should be renamed to N/A, as well if id doesn't exist in one of the other tables. And I would like to get DISTINCT title_id.

CodePudding user response:

You can UNION ALL the tables together, then use string aggregation

SELECT
  t.title_id,
  STRING_AGG(ISNULL(t.team, 'N/A'), ', ') WITHIN GROUP (ORDER BY t.ordering) AS team
FROM (
    SELECT 
      a.title_id,
      a.homeTeam AS team,
      1 AS ordering
    FROM a

    UNION ALL

    SELECT 
      b.title_id,
      b.awayTeam
      2
    FROM b

    UNION ALL

    SELECT 
      c.title_id,
      c.homeTeam
      3
    FROM c
) t;

CodePudding user response:

Try this:

select
    a.title_id,
    CONCAT(
        CASE WHEN a.homeTeam is NULL THEN 'N/A' ELSE a.homeTeam END,
        CASE WHEN b.awayTeam is NULL THEN 'N/A' ELSE b.awayTeam END,
        CASE WHEN c.homeTeam is NULL THEN 'N/A' ELSE c.homeTeam END,
        ) 'Teams',
from TableA a
    join TableB b on a.title_id = b.title_id
    join TableC c on c.title_id = a.title_id

As for the DISTINCT title_id, it should be unique by default as I assume it is used as the key in each of the tables.

  •  Tags:  
  • Related