Forum Discussion

AR_hgt's avatar
AR_hgt
Copper Contributor
Nov 16, 2021

Join different table columns into one using Azure SQL

Dear All,

Good Day!

I need your help in below scenario in Azure SQL.
I would like to join 3 tables data into 1 table with getting columns value as shown below,

Hope you could help me with writting sql query. Looking forward for it.
Thank you in advance.

1 Reply

  • MCarr10's avatar
    MCarr10
    Copper Contributor
    This question is old and I am sure you already found a solution. I thought I would post a solution in case someone else has the same question. The tables needed to be unioned together. Because each table contains unique data, union all is the more efficient way to go.

    SELECT [Location]
    ,[Date]
    ,SUM(TableACount) AS TableACount
    ,SUM(TableBCOunt) AS TableBCount
    ,SUM(TableCCount) AS TableCCount
    FROM (
    SELECT [Location]
    ,[Date]
    ,TableACount
    ,NULL As TableBCount
    ,NULL As TableCCount
    FROM TableA
    UNION ALL
    SELECT [Location]
    ,[Date]
    ,NULL
    ,TableBCount As TableBCount
    ,NULL As TableCCount
    FROM TableB
    UNION ALL
    SELECT [Location]
    ,[Date]
    ,NULL As TableACount
    ,NULL As TableBCount
    ,TableCCount
    FROM TableC
    ) AS X
    GROUP BY [Location], [Date]
    ORDER BY [Date] ASC, [Location] DESC

Resources