I have an odd question. I have three tables all with different information but a few common columns. I want to get a sum from the tables, but I also want to know which table the data came from. I can do the following and get my sum, but how to know which table it came from?
select
CustName, CustNumber, cost, sum(QUANTITY) as total
from
(select CustName, CustNumber, cost, QUANTITY from table1
union all
select CustName, CustNumber, cost, QUANTITY from table2
union all
select CustName, CustNumber, cost, QUANTITY from table3) x
WHERE CustNumber = '894047001034' AND CustName = 'Joseph Smythe'
group by CustName;
2
Answers
This is untested code so some tweaking might be needed.
You could add the tablename as an extra column from your queries and then add the table name to your outer select;
Or just change the group by of the previous nice suggestion with
GROUP BY CustName, CustNumber, cost, table_name