Skip to content
Advertisement

Adding a column to pull in name of the table in union query

I have 2 queries that I want to combine before exporting to Excel. I used a UNION query to do so, which worked great. Now I want to create a column that says the name of the table it came from. What would be the best way to do this? In the 2 separate queries or the joined query?

For reference:

SELECT qry_xxx.Sold_Date, qry_xxx.Sold_Year, qry_xxx.Sold_Month
FROM qry_xxx

UNION SELECT qry_yyy.Sold_Date, qry_yyy.Sold_Year, qry_yyy.Sold_Month
FROM qry_yyy;

Advertisement

Answer

Please try the query below:

SELECT qry_xxx.Sold_Date, qry_xxx.Sold_Year, qry_xxx.Sold_Month, 'qry_xxx' as NameOfTable
FROM qry_xxx

UNION 

SELECT qry_yyy.Sold_Date, qry_yyy.Sold_Year, qry_yyy.Sold_Month, 'qry_yyy' as NameOfTable
FROM qry_yyy;

EDIT:

You can use “group by” after using your first query as a subquery like below:

Select max(Sold_Date) as MaxSoldDate,
       max(Sold_Year) as MaxSoldYear,
       max(Sold_month) as MaxSoldMonth,
       NameOfTable
FROM (
    SELECT qry_xxx.Sold_Date, qry_xxx.Sold_Year, qry_xxx.Sold_Month, 'qry_xxx' as NameOfTable
    FROM qry_xxx

    UNION 

    SELECT qry_yyy.Sold_Date, qry_yyy.Sold_Year, qry_yyy.Sold_Month, 'qry_yyy' as NameOfTable
    FROM qry_yyy;
     ) x
group by NameOfTable
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement