SQL: JOIN problem using temp tables and one column - sql

I am created two temp tables in which TABLE1 contains all the items and TABLE2 only has the partial list of TABLE1. How can I find out which parts TABLE 1 has that TABLE2 doesn't have or vice versa? Please keep in mind, the temp table only has one column due to the DISTINCT statement.
I do have to use Joins but my thought is if I JOIN on the individual columns of each table and then in the Where clause state that e.g. column 1 is not equal column 2, it's contradicting.
IF EXISTS (
SELECT *
FROM tempdb.dbo.sysobjects
WHERE id = Object_id(N'tempdb..#TABLE1')
)
BEGIN
DROP TABLE #TABLE1
END
IF EXISTS (
SELECT *
FROM tempdb.dbo.sysobjects
WHERE id = Object_id(N'tempdb..#TABLE2')
)
BEGIN
DROP TABLE #TABLE2
END
------------------------------------------------
select distinct 1.parts as #TABLE1 from List1 1 --- MAIN LIST
select distinct 2.parts as #TABLE2 from List2 2 --- ADDITIONAL LIST
select *
from #TABLE2 left join
#TABLE1
on 2.parts = 1.parts
where 2.parts <> 1.parts

Your where clause is undoing the left join. I would recommend not exists:
select t1.*
from #table1 t1
where not exists (select 1 from #table2 t2 where t2.parts = t1.parts);

Related

Insert into each column of a table values based on conditions

I have a table of products like this:
I want to delete duplicate rows in this table and use the Ids in other tables, so I used a temporary table to add just the Ids to delete and the Ids to keep:
-- create tmp table
create table #tmp (ProductId_ToKeep int, ProductId_ToDelete int);
-- collect the Products that have a lower id with the same name in the temp table
insert into #tmp (ProductId_ToKeep)
select [ProductId]
from dbo.[Product] t1
where exists
(
select 1
from dbo.[Product] t2
where t2.name = t1.name
and t2.[ProductId] > t1.[ProductId]
);
-- collect the Products that have a higher id with the same name in the temp table
insert into #tmp (ProductId_ToDelete)
select [ProductId]
from dbo.[Product] t1
where exists
(
select 1
from dbo.[Product] t2
where t2.name = t1.name
and t2.[ProductId] < t1.[ProductId]
);
select * from #tmp
After getting what I have in my temp table, I got this result:
I'm asking if any can one help me to put the Ids in each column as I want.
If I followed you correctly, you could use a window function to feed the transcodification table in a single query, like so:
insert into #tmp (ProductId_ToKeep, ProductId_ToDelete)
select *
from (
select
ProductId ProductId_ToDelete,
min(ProductId) over(partition by name) ProductId_ToKeep
from dbo.[Product]
) t
where ProductId_ToDelete != ProductId_ToKeep
The inner query pulls out the smallest ProductId for the given name; the outer query filters on record that should be deleted (ie whose ProductId is not the minimum ProductId for the same name).

How to find extra/different rows in table compared with another table?

I am trying to find the rows that are extra or different when comparing two tables in SQL Server.
For example, #temp1 has 5000 rows and #temp2 has 5125 rows.
I've tried doing
SELECT * FROM #temp1
EXCEPT
SELECT * FROM #temp2
but it returns empty results.
So I tried
SELECT * FROM #temp1
INTERSECT
SELECT * FROM #temp2
and this returns 5000 rows, which is the amount of rows from #temp1, so that shows me that #temp2 contains all the rows that exist in #temp1, but it just has 125 extra rows. I am trying to write a query that shows just those extra 125 rows from #temp2.
You can try this
SELECT *
FROM #table2
WHERE NOT EXISTS
(SELECT *
FROM #table1
WHERE #table1.PK = #table2.PK)
Or
SELECT *
FROM #table2 t1
LEFT JOIN #table2 t2 ON t2.PK = t1.PK
WHERE t2.PK IS NULL
This would work on any of SQL databases
Your order is not correct
SELECT * FROM #temp2
EXCEPT
SELECT * FROM #temp1
One fun way is:
(SELECT * FROM #temp2
UNION
SELECT * FROM #temp2
) EXCEPT
(SELECT * FROM #temp1
INTERSECT
SELECT * FROM #temp2
)
This just shows the unique rows that are different. It doesn't show which table they were originally in.

Find Set of record rowno from multiple column

I have two sql temp table #Temp1 and #Temp2, and I want to get rowid which contain set of temp table two
E.g. In table Temp2 have 4 record i want to search in temp table #Temp1 which contain userid departmentid set of record
CREATE TABLE #Temp1(rowid INT, userid INT, departmentid int)
CREATE TABLE #Temp2(userid INT, deparetmentid int)
INSERT INTO #Temp1 (rowid,userid,departmentid )
VALUES (1,1,1),(1,2,2),(1,3,3),(1,4,4),(1,2,1),
(2,2,1),(2,2,2),(2,3,3),(2,4,4),
(3,3,1),(3,2,2),(3,3,3),(3,4,4)
INSERT INTO #Temp2 (userid,departmentid )
VALUES (2,1),(2,2),(3,3),(4,4)
DROP TABLE #Temp1
DROP TABLE #Temp2
i want output rowid 2 because it contain set of (2,1),(2,2),(3,3),(4,4)
one thing in rowid also contain same set of record it its have one more row mean
when i search in temp1 table based on rowid 1 then i found 4 record and when i search rowid 2 then it contain 4 record so that it is same set of record which i found
Thanks
You could use:
SELECT rowid
FROM #Temp1 t1
WHERE NOT EXISTS(SELECT userid, departmentid
FROM #Temp1 tx
WHERE tx.rowid=t1.rowid
EXCEPT
SELECT userid, departmentid
FROM #Temp2)
GROUP BY rowid
HAVING COUNT(*) = (SELECT COUNT(*) FROM #Temp2);
Output:
2
Rextester Demo
Let's assume the rows in table1 are unique. Then you can do this using join and group by:
select t1.rowid
from #table1 t1 left join
#table2 t2
on t1.userid = t2.userid and t1.departmentid = t2.departmentid
group by t1.rowid
having count(*) = (select count(*) from #table2 t2) and
count(*) = count(t2.userid) ;
This assumes no duplicates in either table.
Note: This returns rows that are identical to or a superset of the values in the second table.

How to select one of the user defined table rows if other data type is null

I have two user defined table type in SQL server 2012 table #Table1 with column name as ColumnTable1 and #Table2 with one of the columns as ColumnTable2.
I wish to select data from a physical table named employeeData. This table has both the columns(ColumnTable1 and ColumnTable2 in it).
What I want is when both #table1 and #table2 have data, then values matching from the both the UDT in employeeData should be returned. If only one of them, then values matching from that table should be returned and if both are null, then all the data from Employeedata table must be returned.
I tried a query which works fine of both of them are not null.
SELECT * FROM employeeData WHERE
(((NOT EXISTS (SELECT 1 FROM #Table1) OR ColumnTable1 IN (SELECT
ColumnTable1 FROM #Table1)) AND (NOT EXISTS (SELECT 1 FROM #Table2)
OR ColumnTable2 in (SELECT ColumnTable2 FROM #Table2)))
PS: this example is for only two tables, I may need to add new such user defined tables in future for similar filtering.
try this
select t.*
from employeeData t
left join #Table1 t1 on t1.ColumnTable1 =t.ColumnTable1
left join #Table2 t2 on t2.ColumnTable2 =t.ColumnTable2
where
not (t1.ColumnTable1 is null and exists (select top 1 1 from #Table1))
and
not (t2.ColumnTable2 is null and exists (select top 1 1 from #Table2))

Update table value by adding from other table

Can you please help me out with the below issue?
I have a table like below.
Table-1
Sales_RepID-- Name-- Products_Count
1-- ABC-- 2
2-- XYZ-- 4
3-- XXX-- 3
Table-2
Order_ID-- Sales_RepID-- Products_Count
1001-- 2 -- 2
1002-- 1 -- 1
1003-- 2 -- 1
1004-- 3 -- 3
1005-- 2 -- 2
Table - 1 Result
Sales_RepID, --Name, --Products_Count
1-- ABC --3
2-- XYZ --9
3-- XXX --6
I want to add table-2 Products_Count to Table-1 Products_Count for each Sale_RepID in the table-1
Can you please help with SQL Query?
My database is MS SQL SERVER
For MS SQL Server, please try:
UPDATE T
SET T.Products_Count=T.Products_Count+x.VSum
FROM Table1 T JOIN
(
SELECT DISTINCT
Sales_RepID,
SUM(Products_Count) OVER (PARTITION BY Sales_RepID) VSum
FROM
Table2
)x ON T.Sales_RepID=x.Sales_RepID
create table table1(sales_repId int,name varchar(10),product_count int);
create table table2(order_id int,sales_repId int,product_count int);
insert into table1 values(1,'ABC',2);
insert into table1 values(2,'XYZ',4);
insert into table1 values(3,'XXX',3);
insert into table2 values(1001,2,2);
insert into table2 values(1002,1,1);
insert into table2 values(1003,2,1);
insert into table2 values(1004,3,3);
insert into table2 values(1005,2,2);
select a.sales_repid,name,a.product_count+sum(b.product_count)
from table1 a
inner join table2 b
on a.sales_repid=b.sales_repid
group by a.sales_repid,name,a.product_count
order by a.sales_repid
UPDATE
update table1
set product_count = netProduct
from (
select a.sales_repid,name,a.product_count+sum(b.product_count) as netProduct
from table1 a
inner join table2 b
on a.sales_repid=b.sales_repid
group by a.sales_repid,name,a.product_count
) z
inner join table1 x
on z.sales_repid=x.sales_repid
TRY THIS
DECLARE #TABLE1 AS TABLE( Sales_RepID INT,Name VARCHAR(100), Products_Count int)
DECLARE #TABLE2 AS TABLE( Order_ID INT,Sales_RepID INT, Products_Count int)
INSERT INTO #TABLE1
VALUES(1,'ABC',2),(2,'XYZ',4),(3,'XXX',3)
INSERT INTO #TABLE2
VALUES(1001,2,2),(1002,1,1),(1003,2,1),(1004,3,3),(1005,2,2)
SELECT * FROM #TABLE1
SELECT * FROM #TABLE2
UPDATE T1
SET T1.Products_Count = T1.Products_count + total
FROM #TABLE1 T1
CROSS APPLY (
SELECT total= sum(Products_count)
FROM #Table2 T2
WHERE T1.Sales_RepID =t2.Sales_RepID ) Z
To output as a select:
select
t1.Sales_RepID,
t1.Name,
t1.Products_Count + sum(t2.Products_Count)
from table1 t1
left join table2 t2 on t2.Sales_RepID = t1.Sales_RepID
To update the total in table1, adding the total from table2:
update table1 set
Products_Count = Products_Count + (
select sum(Products_Count)
from table2
where Sales_RepID = table1.Sales_RepID)
These queries will work in all SQL dialects.
MS SQL Server has a special syntax for updating using a join, which will perform much better than the universal update syntax above:
update t1 set
t1.Products_Count = t1.Products_Count + t2.Products_Count
from table1 t1
join (select Sales_RepID, sum(Products_Count) Products_Count
from table2
group by Sales_RepID) t2
on t2.Sales_RepID = t1.Sales_RepID;
See a live demo of this update statement executing on SQLFiddle.
Note that this is an unusual query. Typically, such denormalized values are not cumulative: they are a determinable calculated value, which in this case wold be simply the sum, not the existing value plus the sum. Your design means that the query can only be executed once. After than you'll be repeatedly re-adding the total from table2.
Consider redesigning your tables to have the straight sum from table2 in table1, ie:
update t1 set
t1.Products_Count = t2.Products_Count
from table1 t1
join (select Sales_RepID, sum(Products_Count) Products_Count
from table2
group by Sales_RepID) t2
on t2.Sales_RepID = t1.Sales_RepID;