SQL Server Union All with one different column - sql-server

I am using union all function inside two tables. Two tables are exactly the same except one column.
Here is my code:
SELECT x.InventoryTransTempID
,x.InventoryTransID
FROM (
SELECT *
FROM InventoryTransTemp
UNION ALL
SELECT *
FROM InventoryTrans
) x
The only column which is different is the Identity column. In first table is called InventoryTransTempID and in Second InventoryTransID. Is there any way to inform sql server that if column name is InventoryTrans just renamed it to InventoryTransTempID.
My exception is:
Invalid column name 'InventoryTransID'.

This error happens because when you perform union operation between two columns and try to get output in one column the name of column is the name of upper one column name as shown below.
Select 'a' as column1
union all
Select 'b' as column2
The output will be here
column1
-------
a
b
Here as per the above statement column2 is mixed with column1, So you can not get both the column name in outer query.
To check the column name you should first check the output of the inner query which is as below.
select * from InventoryTransTemp union all select * from InventoryTrans

The result of UNION ALL is all rows from both tables and the names of the columns are taken from the 1st query of the unioned queries.
So you can't have in the results both column names.
In this query:
select * from InventoryTransTemp
union all
select * from InventoryTrans
the column's name will be InventoryTransTempID,
and in this query:
select * from InventoryTrans
union all
select * from InventoryTransTemp
the column's name will be InventoryTrans.
You can change the name if you alias it in the 1st query.

Related

Querying a table with an additional column containing table name

List item
I am looking for a way query to query a table and add a column with the table name, without explicitly writing the actual 'tablename' within the select statement. Is there a way to do this?
For example I want;
Table name: Construction
The original columns would be Modif_num, modif_desc.
I'd like a query with these results;
The original columns would be Modif_num, modif_desc.
MODIF_NUM TABLE_NAME MODIF_DESC
2 Construction Quality
2 Construction Quality
2 Construction Quality
2 Construction Quality
A regular select * would yield
MODIF_NUM MODIF_DESC
2 Quality
2 Quality
2 Quality
2 Quality
In this instance i would use excel.
column A : table name
column B : ="select cast('"&A1&"' as nvarchar(50)) as tablename ,* into TARGETTABLE from "& A1
Then fill column A with all your table names.. then copy and paste column B into SSMS
This assumes based on your comment this is a one off task. If its not a one off task use the same logic to generate a bunch of strings and execute them.
Ah Wait sorry you cannot do select into repeatedly, what am i thinking.. sorry more like this:
In your select statement you can return a column based on a string, for example:
SELECT 'Construction' As Table_Name, MODIF_NUM FROM MyTable
OR
SELECT 'Construction' As Table_Name, * FROM MyTable
To bring them together, a UNION may work:
SELECT 'Construction' As Table_Name, MODIF_NUM, MODIF_DESC FROM tblConstruction
UNION ALL
SELECT 'Demolition' As Table_Name, MODIF_NUM, MODIF_DESC FROM tblDemolition
UNION ALL
SELECT 'Reconstruction' As Table_Name, MODIF_NUM, MODIF_DESC FROM tblReconstruction
Does this help?
Try this query:
SELECT TABLE_NAME, a.*
FROM [Construction] a,
INFORMATION_SCHEMA.TABLES

Joining two tables having duplicate data in both columns on the base of which we are joining

I have two tables. A column named CardName is in first table. There is duplicate data in this columns. That column also exists in second table. There is a column named amount related to each cardName also in second table. What i want is to select distinct CardName from 1st table and and take sum of all the amounts from second column whose cardname is in first table. BUT first table cardname should be distinct.
what should i do?
select name,sum(amount) from tableB
where name in (select distinct name from TableA)
group by name
use distinct keyword. Distinct will give you only the unique name from TableA and from the sub query result we are getting name and sum from tableB
Refer this : http://technet.microsoft.com/en-us/library/ms187831(v=sql.105).aspx
From you comment below UPDATE
with cte (name) as
(
select distict name from TableA
)
select cte.name,ISNULL(sum(count),0) from TableB as B
left join cte.name = B.name

How to union two tables with Orderby clause?

I have two tables - table1 and table2. Both contains two columns - rollnum,name. Now I wants to select all rows from table1 and randomly 5rows from table2. I have written like this
select rollnum,name from table1 union (select top 5 rollnum,name from table2 order by NEWID())
but it shows an error ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator. please help . I think the mistake is at NEWID(). here rollnum is primary key
The problem is with the brackets. Try this instead
select rollnum,name from table1
union
select * from (select top 5 rollnum,name from table2 order by NEWID()) t
If you could have duplicate entries you may want to consider a union all instead of union
Try This..
SELECT rollnum AS 'NewID' ,
name
FROM table1
UNION
SELECT TOP 5
rollnum ,
name
FROM table2
ORDER BY NewID
NEWID() is a function which assign a value to a variable declared as the uniqueidentifier data type

Get one list from two table columns

I have two tables in SQL Server which have two similar columns.
table1 (
partID, PartName, ....
)
table2 (
sekId, Part2Name, ....
)
I need to populate one combobox in vb.net with the cummulated values of PartName and Part2Name so that the list can appear like being sourced from one single column, because the user might require from either. The combobox must be one that's how the design has it. Is there an SQL statement to sort me out?
U get all valuel like this:
SELECT PartName FROM table1
UNION
SELECT PartName From table2
Using the UNION T-SQL statement will join the two tables togheter
SELECT partID as IDNumber, PartName as Name FROM table1
UNION
SELECT sekID as IDNumber, Part2Name as Name From table2
ORDER BY Name
and sort the union using the renamed column

How to use UNION while inserting in a table using SELECT clause from many tables in SQL Server 2000

I am using SQL Server 2000. I have multiple criterias which i have to use to extract different sets of records from mumtiple table in another table. I am using
INSERT INTO T1(A,B)
(SELECT E,R FROM T2)
UNION
(SELECT Z,X FROM T3)
Query analyzer is throwing error that while using UNION, you should use ORDER BY clause with SELECT. Even after doing that i m not able to union two different queries which are returing same columns in their select clause.
What is the right way to insert using SELECTS with UNIONS and ORDER BY.
The pseudo is too cryptic (reduced?)
It is very unlikely to get 2 columns per cross join of 2 tables in each of the union components
INSERT INTO T1(A,B)
(SELECT * FROM E,R)
UNION
(SELECT * FROM Z,X)
Note: If you have ANY order by clause at all, it must be at the end of the union
INSERT T1(A,B)
SELECT P,Q FROM E,R
UNION
SELECT R,S FROM Z,X
#updated based on error text "Server: Msg 104, Level 15, State 1, Line 1 ORDER BY items must appear in the select list if the statement contains a UNION operator"
This occurs when you have a union that attempts to perform ORDER BY on a column that does not appear in the result. Consider a normal ORDER BY involving non-selected columns
select top 10 name from syscolumns order by xtype
The rows are consistent and the query can be satisfied. However, if you did
select top 10 name from syscolumns where xtype > 50
union all
select top 10 name from syscolumns where xtype < 50
order by xtype
EVEN IF xtype exists in both parts of the UNION, but the time it gets presented to ORDER BY (which works at the END over the entire result set), the column is not there. You would have to rewrite it (if you didn't want to show xtype) as
select name from (
select top 10 name, xtype from syscolumns where xtype > 50
union all
select top 10 name, xtype from syscolumns where xtype < 50
) x
order by xtype
Hope that helps

Resources