简体   繁体   中英

Want to add a New column in MS Access query via SQL

I have 3 tables they all have the same column header Name, Number I have joined them using the union command as shown below:

SELECT Name, Number
FROM table1
Union all
select name, number
from table2
UNION ALL select name, number
from table3;

Every thing is right up till here. Now I want to add a new column which should contain the information about from which table this data have been taken. I am using the alter table command but it gives error.

Kindly help me. I am working on MS access 2007.

Just add it in as a column in each subquery:

SELECT Name, Number, 'table1' as which
FROM table1
Union all
select name, number, 'table2' as which
from table2
UNION ALL
select name, number, 'table3' as which
from table3;

ALTER TABLE only works on actual tables, not query results.

You simply need to add the information as a pseudo-column to your current query:

SELECT 
  Name, Number, 'Table1' as TableName
FROM 
  table1
Union all
select 
  name, number, 'Table2'
from 
  table2
UNION ALL 
select 
  name, number, 'Table3'
from table3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM