Insert into each column of a table values based on conditions - sql

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).

Related

SQL: JOIN problem using temp tables and one column

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);

I need to insert the values from the second table to the first table whenewer the ID matches

I have 2 tables . Below is the fields description.
1st table Fields: EmployeeID, Name, EmployeeStatus, PreferredName
2nd table Fields: EmployeeID, PreferredName
I need to insert the values of PreferredName from 2nd table to the first table whenever EmployeeID matches. Currently all values of PreferredName in the 1st table are null. If no match by EmployeeID they should remain null . This is SQL Server.
I am trying something like :
insert into [Table1] PreferredName values
SELECT
[PreferredName]
FROM [Table2]
where [EmployeeID] in (SELECT EmployeeID FROM [Table1]
I think you actually want to UPDATE the table, not INSERT new data. For that, you can use an UPDATE with JOIN query:
UPDATE table1
SET table1.PreferredName = table2.PreferredName
FROM table1
JOIN table2 ON table2.EmployeeID = table1.EmployeeID
Demo on dbfiddle
you can use not exists keyword
insert into table1 (preferredname)
select t2.preferredname
from table2 t1 where
not exists (select 1 from table1 t1 where t1.preferredname = t2.preferredname)

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.

Write subquery in xml.exist()

I have a table with one column:
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp
CREATE TABLE #tmp
(
data XML
)GO
with one record:
INSERT INTO #tmp
VALUES ( N'<RelevanExpertXML><Tel><RelevanExpert>1</RelevanExpert></Tel><Tel><RelevanExpert>2</RelevanExpert></Tel></RelevanExpertXML>')
and another tale with one column
CREATE TABLE #tmp2
(
id int
)
GO
and i want to write this query:
select *
from #temp
where xml.exist('/RelevanExpertXML/Tel/RelevanExpert[(text()) = [select id from #temp2]]') = 1
in fact i want to write sub query in exist(), but i get error, and also i can't change from clause and select list, only i can change where clause.
thanks for help.
you can use this query:
select *
from #tmp
where exists
(
select *
from #tmp2 as t
where
#tmp.data.exist('/RelevanExpertXML/Tel/RelevanExpert[(text()) = sql:column("t.id")]') = 1
)
but it will return you the whole xml. If you want to split xml by rows, you have to use nodes() function in the from clause.
You can write
select *
from #tmp, #temp2
where data.exist('/RelevanExpertXML/Tel/RelevanExpert[text()] = sql:column("id")')=1
But I don't think it will give you the results you're after.
You may be after something more like
select t.r.value('.','int')
from #tmp temp
cross apply data.nodes('/RelevanExpertXML/Tel/RelevanExpert') t(r)
inner join #temp2 t2 on t.r.value('.','int') = t2.id

selecting row from one table and insert into other table

Selecting rows from table1 which do not exists in table2 and inserting it in table2
like
Images
id type name
502 1 summer.gif
SEOImages
id idimage ... ...
1000 501 ... ...
Now I want to select all the rows from Images table whose id does not match idimage SEOImages table and insert those rows into the SEOImages table.
Approach :
Insert into Table2
select A,B,C,....
from Table1
Where Not Exists (select *
from table2
where Your_where_clause)
Example :
SQLFiddelDemo
Create table Images(id int,
type int,
name varchar(20));
Create table SEOImages(id int,
idimage int);
insert into Images values(502,1,'Summer.gif');
insert into Images values(503,1,'Summer.gif');
insert into Images values(504,1,'Summer.gif');
insert into SEOImages values(1000,501);
insert into SEOImages values(1000,502);
insert into SEOImages values(1000,503);
insert into SEOImages
select 1000,id
from Images I
where not exists (select *
from SEOImages
where idimage =I.id);
INSERT INTO SeoImages
(IdImage)
SELECT ID
FROM Images
WHERE ID NOT IN (SELECT IDIMAGE FROM SEOImages)
The query:
SELECT * FROM Images
WHERE id NOT IN (SELECT idimage FROM SEOImages)
should bring out those rows from Images that do not have a corresponding ID in SEOImages, assuming they are both of the same type.
Alternatively, using a JOIN:
SELECT i.* FROM Images i
LEFT OUTER JOIN SEOImages s on i.id = s.imageId
WHERE s.imageId IS NULL
INSERT INTO SEOImages
SELECT *
FROM Images
WHERE NOT EXISTS (SELECT 1
FROM Images t1, SEOImages t2
WHERE t1.id=t2.id) ;