Skip to content
Advertisement

Combine Data from Different tables in same SQL Database along with the Table Name

I am trying to get data from Multiple Tables in a same SQL Database along with the Table name from which those are taken from.

    Select [timestamp]
      ,[User ID]
      ,[HCA Location Code]
      ,[HCA Lead]
      ,[PC Location Code]
      ,[Approval Administrator]
      ,[Time Sheet Admin_]
    FROM
    (SELECT * FROM [LIVE].[dbo].[LIVE Database1$User Setup]
    Union ALL
    SELECT * FROM [LIVE].[dbo].[LIVE_Database2$User Setup]
    Union ALL
    SELECT * FROM [LIVE].[dbo].[LIVE_Database3$User Setup]) data
    GROUP BY
      [timestamp]
      ,[User ID]
      ,[HCA Location Code]
      ,[HCA Lead]
      ,[PC Location Code]
      ,[Approval Administrator]
      ,[Time Sheet Admin_]
    HAVING count(*)!=2
   For value like below

enter image description here

Advertisement

Answer

Select [User ID]
        ,[HCA Location Code]
        ,[HCA Lead]
        ,[PC Location Code]
    ,[Approval Administrator]
    ,[Time Sheet Admin_]
    , Table_Name
FROM
(
    Select [User ID]
            ,[HCA Location Code]
            ,[HCA Lead]
            ,[PC Location Code]
            ,[Approval Administrator]
            ,[Time Sheet Admin_]
            ,'Table1' AS Table_Name
    FROM [DB].[dbo].[UAT Table1$User Setup] as Tablename1
    Union ALL
    Select [User ID]
            ,[HCA Location Code]
            ,[HCA Lead]
            ,[PC Location Code]
            ,[Approval Administrator]
            ,[Time Sheet Admin_]
            ,'Table2' AS Table_Name
    FROM [DB].[dbo].[UAT Table2$User Setup]as Tablename1
    Union ALL
    Select [User ID]
            ,[HCA Location Code]
            ,[HCA Lead]
            ,[PC Location Code]
            ,[Approval Administrator]
            ,[Time Sheet Admin_]
            ,'Table3' AS Table_Name
    FROM [DB].[dbo].[Table3$User Setup]as Tablename1) data

GROUP BY
      [User ID]
      ,[HCA Location Code]
      ,[HCA Lead]
      ,[PC Location Code]
      ,[Approval Administrator]
      ,[Time Sheet Admin_]
      ,Table_Name
HAVING count(*)!=2
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement