Merge 2 tables into 1 single Table in T-SQL - sql-server

How do I merge 2 tables into 1 table in T-SQL? I tried merging with full outer join which helps in joining 2 tables but with "customer Account" 2 times. I need all the columns from table A and Table B with only once "Customer Account Field" and all the rest of the columns from table A and Table B.ields.
Here is my example in more detail:
Table A - my first Table with 5 columns:
Table B - my second table with 6 columns:
I'm expecting the output like this:
Output with all fields in table A and in Table B but the common field only once:
Thanks a lot.

Add the required(all) columns from t1 and t2 to the select statement
SELECT COALESCE(t1.customeraccount, t2.customeraccount) as customeraccount,
t1.BasicCardType,
t2.MonthlySet
FROM table1 t1
FULL JOIN table2 t2 ON t1.customeraccount = t2.customeraccount;

(Edited based on comments): Join the tables on the CustomerAccount ID field (giving you entries that exist in both tables), then add a union for all entries that only exist in table A, then add a union for entries that only exist in table B. In principle:
-- get entries that exist in both tables
select Table_A.CustomerAccount, TableAField1, TableAField2, TableBField1, TableBField2
from Table_A
join Table_B on Table_A.CustomerAccount = Table_B.CustomerAccount
-- get entries that only exist in table_a
union select Table_A.CustomerAccount, TableAField1, TableAField2, null, null
from Table_A
where Table_A.CustomerAccount not in (select CustomerAccount from Table_B)
-- get entries that only exist in table_B
union select Table_B.CustomerAccount, null, null, TableBField1, TableBField2
from Table_B
where Table_B.CustomerAccount not in (select CustomerAccount from Table_A)

Related

Best way to attack a confusing SQL issue in inserting data into a TEMP table

I'm working in SQL Server 2016. Confusing problem with SQL issue. I have a TEMP table that contains unique rows. I have to insert 5 PRODUCTID values for each row each row based on another column value, AgentNo, in this temp table. The PRODUCTID value, there are 5 of them, comes from another table but there is no relationship between the tables. So my question is how do I insert a row for each ProductID into this temp table for each unique row that is currently in the temp table.
Here is a pic of the TEMP table that requires 5 rows for each:
Here is a pic of what I'm needing to come away with:
Here is my SQL code for both TEMP tables:
IF OBJECT_ID('tempdb..#tempTarget') IS NOT NULL DROP TABLE #tempTarget
SELECT 0 as ProductID, 1 as [Status], a.AgentNo, u.UserID, u.[Password], 'N' as AdminID, tel.LocationSysID --, tel.OwnerID, tel.LocationName, a.OwnerSysID, a.AgentName
INTO #tempTarget
FROM dbo.TEST_EvalLocations tel
INNER JOIN dbo.AGT_Agent a
ON tel.LocationName = a.AgentName
INNER JOIN dbo.IW_User u
ON a.AgentNo = u.UserID
WHERE tel.OwnerID = 13313
AND tel.LocationSysID <> 15434;
SELECT * FROM #tempTarget WHERE LocationSysID NOT IN (15425, 15434);
GO
-- Create source table
IF OBJECT_ID('tempdb..#tempSource') IS NOT NULL DROP TABLE #tempSource
SELECT DISTINCT lpr.ProductID
INTO #tempSource
FROM dbo.Eval_LocationProductRelationship lpr
WHERE lpr.ProductID IN (16, 15, 13, 14, 12) --BETWEEN 15435 AND 15595
Sorry I could not get this into a DDL file as these are TEMP tabless. Any help/direction would be appreciated. Thanks.
CROSS JOIN will be the best solution for your case.
If you only want 5 rows for each data in First table means, simply use the below cross join query.
SELECT B.ProductID,
A.[Status],
A.AgentNo,
A.UserID,
A.[Password] AS Value,
A.AdminID,
A.LocationSysID
FROM #tempTarget A
CROSS JOIN tempSource B
If you want additional row with 0, then you have to insert a 0 into your second temp table and use the same query.
INSERT INTO #tempSource SELECT 0
If i understand correctly following is the scenario,
One Temp table has all the content.
select * from #withoutProducts
product table
select * from #products
Then following is the query your are looking for
select a.ProductID,[Status],AgentNo,UserID,[value]
from #products a cross join #withoutProducts b
order by AgentNO,a.productID

SQL query performance for huge data

I have a query:
SELECT c.somecolumn,p.someothercolumn
FROM table1 co
INNER JOIN table2 p(NOLOCK) ON co.COLUMN = p.COLUMN
INNER JOIN table3 c(NOLOCK) ON co.column11 = c.column11
WHERE co.filterColumn = 1
Table2 is a junction table and the join between table1 and table2 is on a column without distinct values (that’s the requirement and can't be changed) and hence there are cross joins.
Output of this query results in 180 million records.
Record count:
table 1: 2 190 561
table 2: 568 277
table 3: 300 150
How to optimize the above query? Execution plan:
Make sure you at least have indexes on the columns in the joins that include the columns you're returning (for example, in table2, you should have a non-clustered index that is keyed on "p.COLUMN" and includes "p.someothercolumn". For table 3, key on c.column11 and include c.somecolumn. You should have an index on table1.filtercolumn.
Consider also, that you have to return 180 million rows to the caller, that takes time. Try just inserting that data into a throwaway table just to keep the network load time out of your equation.
These could be ideally the indexes that are required:
For table1 - filtered index on COLUMN and column11 where co.filterColumn = 1
For table2 - Index on COLUMN include someothercolumn
For table3 - Index on column11 include somecolumn
SELECT c.somecolumn
,tmp.someothercolumn
FROM table1 co
INNER JOIN table3 c(NOLOCK) ON co.column11 = c.column11
AND co.filterColumn = 1
CROSS APPLY (SELECT TOP (1) p.SomeOtherColumn
FROM table2 p(NOLOCK)
WHERE p.COLUMN = co.Column) tmp

sql insert query clause

I have a table A which contains fields
ChangeID DistributionID OutletBrandID
and Table B contains
ID DistributionID OutletBrandID
I need to insert data in table A from table B only if the distributionID and OutletBrandID combination doesn't exist already. Therefore I can't simply use the IN clause as it needs to be a combination.
Assuming that ChangeID and ID should match between the tables:
INSERT INTO TableA (ChangeID, DistributionID, OutletBrandID)
SELECT b.ID, b.DistributionID, b.OutletBrandID FROM TableB b
LEFT OUTER JOIN TableA a ON a.DistributionID=b.DistributionID
AND a.OutletBrandID = b.OutletBrandID
WHERE
a.OutletBrandID IS NULL
AND
a.DistributionID IS NULL

SQL left join table with double sum record

I have two tables (dw and click) and using left join to join it if match the date.
both tables have date 2016-06-01 (dw table has 1 record and click table has 2 records). I want to sum the column winloss in dw table, but since click table has 2 record with the date 2016-06-01 and caused the winloss double sum. But i just want sum the winloss in dw table. Any suggestion? Please refer to image below.
You can do this with a temp table or a common table expression. Here is with a temp.
If object_id('tempdb..#temp') is not null drop table #temp
select
sum(winloss) as winloss,
updated
--add any other columns you want
into #temp
group by
updated
--add other columns to group
select
t.updated,
t.winloss,
c.*
from #temp t
left join click on c.trandate = t.updated
Try this:
SELECT *
FROM DW D
INNER JOIN CLICK C
ON C.CLICKED = D.CLICKCOUNT
AND C.TRANDATE = D.UPDATED
Try this
SELECT dw.[updated]
,sum(distinct [winloss])
from dw,Click
where dw.updated = Click.trandate
FROM dw, Click
group by dw.updated

insert results of join in SQL server 2005

I have two tables with more than 800 rows in each.Table names are 'education' and 'sanitation'.The column name 'ID' is common in both the tables.Now i want to join these both tables as full outer join and i want to save the results of this table as a new table.I can join it very easily,But how to save those data's as a new table.Please help Me.
select * into bc from education e join sanitation s on e.id=s.id
I have around 30 columns in each table.So i can not explicitly create table schema for a new table.
I want all the columns from both tables.I have 20 tables with each 800 rows.From this 20 tables i want to make one master table taking 'ID' as primary key in all.
Sample Code:
Table one:
create table dummy1(
id int , fname varchar(50)
)
insert into dummy1 (id,fname) values (1,'aaa')
insert into dummy1 (id,fname) values (2,'bbb')
insert into dummy1 (id,fname) values (3,'ccc')
insert into dummy1 (id,fname) values (3,'ccc')
Table Two
create table dummy2(
id int , lname varchar(50)
)
insert into dummy2 (id,lname) values (1,'abc')
insert into dummy2 (id,lname) values (2,'pqr')
insert into dummy2 (id,lname) values (3,'mno')
Now Create new table 3
create table dummy3(
id int , fname varchar(50),lname varchar(50)
)
Insert Query for table 3 look like
insert into dummy3 (id,fname,lname)
(select a.id,a.fname,b.lname from dummy1 a inner join dummy2 b on a.id=b.id)
Table 3 will contain table1, table2 data
Follow below:
SELECT t1.Column1, t2.Columnx
INTO DestinationTable
FROm education t1
INNER JOIN sanitation t2 ON t1.Id = t2.Id
EDIT:
SELECT * will not work for you because you have a column ID which exists in both the tables. So the above solution will work you.
EDIT:
1- You can temporarily rename the Id column in one table, then try
2- SELECT *
INTO DestinationTable
FROm education t1
INNER JOIN sanitation t2 ON t1.Id = t2.Id
3- Revert the column name back to Id.

Resources