I have the following query that is returning two columns of data UserID & ServiceID from tables a & b
SELECT a.UserID, b.ServiceID FROM TableA a
JOIN TableB b
ON b.EventID = a.EventID
WHERE a.EventID = 1892286
AND a.Attendance IN (1,2)
The above query returns the following data set:
UserID ServiceID
1 33
2 44
3 55
I need to UPSERT into table c the following way:
If UserID & ServiceID exist in table c then take current value of column Scheduled from table c and add 1
If UserID & ServiceID do NOT exist in table c then insert record into table c with selected UserID and ServiceID from the above select statement and add 1 into the Scheduled column.
My question is how to do this for every single row that is returned by my select statement to ensure all results are UPSERTED into table c
I'm looking through looping case or if-else statements as possible solutions but any input is appreciated.
My attempt at the above:
IF EXISTS (SELECT sa.UserID as S_UserID, ce.ServiceID as S_ServiceID FROM TableA a
JOIN TableB b
ON b.EventID = a.EventID
WHERE a.EventID = 1892286
AND a.Attendance IN (1,2))
UPDATE TableC c
SET
UserID = S_UserID
ServiceID = S_ServiceID
Scheduled = Scheduled + 1
WHERE UserID = S_UserID
AND ServiceID = S_ServiceID
ELSE
INSERT INTO TableC
(UserID,ServiceID,Scheduled)
VALUES
(S_UserID,S_ServiceID,1)
END
If you are on newer version SQL Server (this question is tagged with sql-server-2016), then you can use the MERGE statement.
Here is a somewhat simplified example based on your post:
--create test tables
CREATE TABLE #a (UserID int);
CREATE TABLE #b (UserID int, ServiceID int);
CREATE TABLE #c (UserID int, ServiceID int, Scheduled int);
--insert some data matching the question
INSERT INTO #a
VALUES(1), (2), (3), (4), (5);
INSERT INTO #b
VALUES (1, 33), (2, 44), (3, 55)
INSERT INTO #c
VALUES(2, 44, 3), (4, 66, 1)
--ensure we have data
SELECT * FROM #a
SELECT * FROM #b
SELECT * FROM #c
--use the MERGE statement
MERGE #c AS tgt
USING(SELECT a.UserID, b.ServiceID FROM #a a JOIN #b b ON a.UserID = b.UserID) src
ON (tgt.UserID = src.UserID AND tgt.ServiceID = src.ServiceID)
WHEN NOT MATCHED THEN
INSERT (UserID, ServiceID, Scheduled)
VALUES(src.UserID, src.ServiceID, 1)
WHEN MATCHED THEN
UPDATE
SET Scheduled += 1;
--check what's been inserted/updated
SELECT * FROM #c
Be aware that MERGE sometimes gave performance implications, so use it with caution. More info about MERGE here.
Hope this helps!
One way to do this is by executing different statements for inserting and updating.
-- INSERT INTO Temporary Table
SELECT sa.UserID,
ce.ServiceID
INTO #tempC
FROM TableA a
JOIN TableB b ON b.EventID = a.EventID
WHERE a.EventID = 1892286
AND a.Attendance IN (1,2)
-- UPDATE Existing ROWS
UPDATE c
SET c.Scheduled = c.Scheduled + 1
FROM #tempC c
INNER JOIN TableC d
ON c.UserID = d.UserID
AND c.ServiceID = d.ServiceID
-- INSERT new rows
INSERT INTO TableC (UserID, ServiceID,Scheduled)
SELECT c.UserID, c.ServiceID, 1
FROM #tempC c
LEFT JOIN TableC d
ON c.UserID = d.UserID
AND c.ServiceID = d.ServiceID
WHERE d.UserID IS NULL
-- DROP temporary table
DROP TABLE #tempC
A loop is not efficient
ca and ce are not valid alias so I had to guess the valid alias
Start with a backup in case you do it wrong.
update c
set c.serviceID = c.serviceID + 1
FROM TableA a
JOIN TableB b
ON b.EventID = a.EventID
and a.EventID = 1892286
AND a.Attendance IN (1,2)
join TableC c
on c.UserID = a.UserID
and c.ServiceID = b.ServiceID;
INSERT INTO TableC (UserID, ServiceID, Scheduled)
SELECT a.UserID, b.ServiceID, 1
FROM TableA a
JOIN TableB b
ON b.EventID = a.EventID
and a.EventID = 1892286
AND a.Attendance IN (1,2)
where not exists (select 1
from TableC c
where c.UserID = a.UserID
and c.ServiceID = b.ServiceID
);
Related
I have two tables Table_A and Table_B. How can I write a conditional SQL that does the following logic
If table A records match table B records on id
then
delete records from table A and Insert records into Table B
How can I do this with SQL most likely using with
delete from Table_A where Exists (select a.id from TABLE_A
join TABLE_B as b on a.id = b.id)
The Insert is:Insert into Table_A (id) select id from TABLE_B
Use a CTE to catch the ids of the deleted records, and re-join these with the b records:
WITH del AS (
DELETE FROM a
WHERE EXISTS ( SELECT *
FROM b
WHERE b.id = a.id
)
returning *
)
INSERT INTO a (id, x, y, z)
SELECT id, x, y, z
FROM b
WHERE EXISTS (
SELECT *
FROM del
WHERE del.id = b.id
);
BTW: you should have very good reasons (such as wanting to activate the triggers) to prefer delete+insert to a update.
I have two tables with identical columns, in an identical order. I have a desire to join across one of the two tables, depending on a subquery condition. For example, assume I have the following schema:
CREATE TABLE b (
bid SERIAL PRIMARY KEY,
cid INT NOT NULL
);
CREATE TABLE a1 (
aid SERIAL PRIMARY KEY,
bid INT NOT NULL REFERENCES b
);
CREATE TABLE a2 (
aid SERIAL PRIMARY KEY,
bid INT NOT NULL REFERENCES b
);
I would like a query, that performs a join across either a1 or a2 based on some condition. Something like:
WITH z AS (
SELECT cid, someCondition FROM someTable
)
SELECT *
FROM CASE z.someCondition THEN a1 ELSE a2 END
JOIN b USING (bid)
WHERE cid = (SELECT cid FROM z);
However, the above doesn't work. Is there some way to conditionally join across a1 or a2, depending on some boolean condition stored in table z?
If the conditions are exclusive (I expect they are): just do both queries and UNION ALL them, with the smart union construct:
WITH z AS (
SELECT cid
, (cid %3) AS some_condition -- Fake ...
FROM b
)
SELECT *
FROM a1
JOIN b USING (bid)
WHERE EXISTS( SELECT * FROM z
WHERE some_condition = 1 AND cid = b.cid )
UNION ALL
SELECT *
FROM a2
JOIN b USING (bid)
WHERE EXISTS( SELECT * FROM z
WHERE some_condition = 2 AND cid = b.cid )
;
A somewhat different syntax to do the same:
WITH z AS (
SELECT cid
, (cid %3) AS some_condition
FROM b
)
SELECT *
FROM a1
JOIN b ON a1.bid = b.bid
AND EXISTS( SELECT * FROM z
WHERE some_condition = 1 AND cid = b.cid )
UNION ALL
SELECT *
FROM a2
JOIN b ON a2.bid = b.bid
AND EXISTS( SELECT * FROM z
WHERE some_condition = 2 AND cid = b.cid )
;
SQL syntax does not allow conditional joins.
Probably the simplest way to achieve a similar effect is to use a dynamic query in a plpgsql function, which may look like this:
create function conditional_select(acid int, some_condition boolean)
returns table (aid int, bid int, cid int)
language plpgsql as $$
declare
tname text;
begin
if some_condition then tname = 'a1';
else tname = 'a2';
end if;
return query execute format ($fmt$
select a.aid, b.bid, b.cid
from %s a
join b using(bid)
where cid = %s;
$fmt$, tname, acid);
end $$;
select * from conditional_select(1, true)
If, like in your example, you have only a few columns that you want to output, you can use the CASE statement for every column:
SELECT CASE z.someCondition THEN a1.aid ELSE a2.aid END AS aid,
CASE z.someCondition THEN a1.bid ELSE a2.bid END AS bid
FROM b
JOIN a1 ON a1.bid = b.bid
JOIN a2 ON a2.bid = b.bid
JOIN someTable z USING (cid);
Depending on the size of tables a1 and a2 and how many columns you have to output, this may or my not be faster than Klin's solution with a function, which is inherently slower than plain SQL and even more so because of the dynamic query. Given that z.someCondition is a boolean value already, the CASE evaluation will be very fast. Small tables + few columns = this solution; large tables + many columns = Klin's solution.
This is my T-SQL
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
inner join [tableA or tableB] on xxxxxxxx
I want join tableA when Profile = Soft and join tableB when Profile = Hard, how can I do just only using T-SQL in one batch?
Thanks
You can't directly do it, but could achieve the same effect with outer joins
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
left outer join tableA ON tableA.x = p1.x AND p1.Profile = 'Soft'
left outer join tableB ON tableB.x = p1.x AND p1.Profile = 'Hard'
where
where
(tableA.x IS NOT NULL and p1.Profile = 'Soft')
or (tableB.x IS NOT NULL and p1.Profile = 'Hard')
Of course, you can choose different tables for inner join operation, but it must be based on some condition or variable.
For Example:
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
inner join tableA A
on Profile='Soft'
AND <any other Condition>
UNION
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
inner join tableB B
on Profile='Hard'
AND <any other Condition>
You can do this in a single statement with the same or similar case statement in your join. Below is sample code using temp tables that joins to 2 different reference tables merged into a single result set using a UNION
DECLARE #ProductDetail TABLE (Id INT, sProfile VARCHAR(100), StID INT, HdID INT)
DECLARE #TableA TABLE (StId INT, Field1 VARCHAR(100))
DECLARE #TableB TABLE (HdId INT, Field1 VARCHAR(100))
INSERT INTO #ProductDetail (Id, sProfile, StID , HdID ) VALUES (1,'Soft',1,1)
INSERT INTO #ProductDetail (Id, sProfile, StID , HdID ) VALUES (2,'Hard',2,2)
INSERT INTO #TableA (StId,Field1) VALUES (1,'Soft 1')
INSERT INTO #TableA (StId,Field1) VALUES (2,'Soft 2')
INSERT INTO #TableB (HdId,Field1) VALUES (1,'Hard 1')
INSERT INTO #TableB (HdId,Field1) VALUES (2,'Hard 2')
SELECT
p1.Id,p1.sProfile,
CASE
WHEN p1.sProfile = 'Soft' THEN StID
WHEN p1.sProfile = 'Hard' THEN HdId
END AS [Profile]
,ReferenceTable.FieldName
FROM
#ProductDetail p1
INNER JOIN
(
SELECT StID AS id, 'Soft' AS sProfile, Field1 AS FieldName
FROM #TableA AS tableA
UNION ALL
SELECT HdID AS id, 'Hard' AS sProfile, Field1 AS FieldName
FROM #TableB AS tableB
)
AS ReferenceTable
ON
CASE
WHEN p1.sProfile = 'Soft' THEN StID
WHEN p1.sProfile = 'Hard' THEN HdID
END = ReferenceTable.Id
AND p1.sProfile = ReferenceTable.sProfile
This will return the following result set:
Id sProfile Profile FieldName
1 Soft 1 Soft 1
2 Hard 2 Hard 2
I'm quite stuck with this problem for sometime now..
How do I sort column A depending on the contents of Column B?
I have this sample:
ID count columnA ColumnB
-----------------------------------
12 1 A B
13 2 C D
14 3 B C
I want to sort it like this:
ID count ColumnA ColumnB
-----------------------------------
12 1 A B
14 3 B C
13 2 C D
so I need to sort the rows if the previous row of ColumnB = the next row of ColumnA
I'm thinking a loop? but can't quite imagine how it will work...
I was thinking it will go like this (maybe)
SELECT
a.ID, a.ColumnA, a.ColumnB
FROM
TableA WITH a (NOLOCK)
LEFT JOIN
TableA b WITH (NOLOCK) ON a.ID = b.ID AND a.counts = b.counts
WHERE
a.columnB = b.ColumnA
the above code isn't working though and I was thinking more on the lines of...
DECLARE #counts int = 1
DECLARE #done int = 0
--WHILE #done = 0
BEGIN
SELECT
a.ID, a.ColumnA, a.ColumnB
FROM
TableA WITH a (NOLOCK)
LEFT JOIN
TableA b WITH (NOLOCK) ON a.ID = b.ID AND a.counts = #counts
WHERE
a.columnB = b.ColumnA
set #count = #count +1
END
If this was a C code, would be easier for me but T-SQL's syntax is making it a bit harder for a noobie like me.
Any help is greatly appreciated!
Edit: sample code
drop table tablea
create table TableA(
id int,
colA varchar(10),
colb varchar(10),
counts int
)
insert INTO TableA
(id, cola, colb, counts)
select 12, 'Bad', 'Cat', 3
insert INTO TableA
(id, cola, colb, counts)
select 13, 'Apple', 'Bad', 1
insert INTO TableA
(id, cola, colb, counts)
select 14, 'Cat', 'Dog', 2
select * FROM TableA
SELECT a.ID, a.ColA, a.ColB
FROM TableA a WITH (NOLOCK)
LEFT JOIN TableA b WITH (NOLOCK)
ON a.ID = b.ID
Where a.colB = b.ColA
ORDER BY a.ColA ASC
you just need to add ORDER BY clause
-- SELECT a.ID, a.ColumnA, a.ColumnB
-- FROM TableA WITH a (NOLOCK)
-- LEFT JOIN TableA b WITH (NOLOCK)
-- ON a.ID = b.ID
-- and a.counts = b.counts
-- Where a.columnB = b.ColumnA
ORDER BY a.ColumnA ASC
This is all you need. Sometimes you have to think simple
select * from table A
order by columnA asc
Scenario:
Let's say I have two tables, TableA and TableB. TableB's primary key is a single column (BId), and is a foreign key column in TableA.
In my situation, I want to remove all rows in TableA that are linked with specific rows in TableB: Can I do that through joins? Delete all rows that are pulled in from the joins?
DELETE FROM TableA
FROM
TableA a
INNER JOIN TableB b
ON b.BId = a.BId
AND [my filter condition]
Or am I forced to do this:
DELETE FROM TableA
WHERE
BId IN (SELECT BId FROM TableB WHERE [my filter condition])
The reason I ask is it seems to me that the first option would be much more effecient when dealing with larger tables.
Thanks!
DELETE TableA
FROM TableA a
INNER JOIN TableB b
ON b.Bid = a.Bid
AND [my filter condition]
should work
I would use this syntax
Delete a
from TableA a
Inner Join TableB b
on a.BId = b.BId
WHERE [filter condition]
Yes you can. Example :
DELETE TableA
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
Was trying to do this with an access database and found I needed to use a.* right after the delete.
DELETE a.*
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
It's almost the same in MySQL, but you have to use the table alias right after the word "DELETE":
DELETE a
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
The syntax above doesn't work in Interbase 2007. Instead, I had to use something like:
DELETE FROM TableA a WHERE [filter condition on TableA]
AND (a.BId IN (SELECT a.BId FROM TableB b JOIN TableA a
ON a.BId = b.BId
WHERE [filter condition on TableB]))
(Note Interbase doesn't support the AS keyword for aliases)
I'm using this
DELETE TableA
FROM TableA a
INNER JOIN
TableB b on b.Bid = a.Bid
AND [condition]
and #TheTXI way is good as enough but I read answers and comments and I found one things must be answered is using condition in WHERE clause or as join condition. So I decided to test it and write an snippet but didn't find a meaningful difference between them. You can see sql script here and important point is that I preferred to write it as commnet because of this is not exact answer but it is large and can't be put in comments, please pardon me.
Declare #TableA Table
(
aId INT,
aName VARCHAR(50),
bId INT
)
Declare #TableB Table
(
bId INT,
bName VARCHAR(50)
)
Declare #TableC Table
(
cId INT,
cName VARCHAR(50),
dId INT
)
Declare #TableD Table
(
dId INT,
dName VARCHAR(50)
)
DECLARE #StartTime DATETIME;
SELECT #startTime = GETDATE();
DECLARE #i INT;
SET #i = 1;
WHILE #i < 1000000
BEGIN
INSERT INTO #TableB VALUES(#i, 'nameB:' + CONVERT(VARCHAR, #i))
INSERT INTO #TableA VALUES(#i+5, 'nameA:' + CONVERT(VARCHAR, #i+5), #i)
SET #i = #i + 1;
END
SELECT #startTime = GETDATE()
DELETE a
--SELECT *
FROM #TableA a
Inner Join #TableB b
ON a.BId = b.BId
WHERE a.aName LIKE '%5'
SELECT Duration = DATEDIFF(ms,#StartTime,GETDATE())
SET #i = 1;
WHILE #i < 1000000
BEGIN
INSERT INTO #TableD VALUES(#i, 'nameB:' + CONVERT(VARCHAR, #i))
INSERT INTO #TableC VALUES(#i+5, 'nameA:' + CONVERT(VARCHAR, #i+5), #i)
SET #i = #i + 1;
END
SELECT #startTime = GETDATE()
DELETE c
--SELECT *
FROM #TableC c
Inner Join #TableD d
ON c.DId = d.DId
AND c.cName LIKE '%5'
SELECT Duration = DATEDIFF(ms,#StartTime,GETDATE())
If you could get good reason from this script or write another useful, please share. Thanks and hope this help.
Let's say you have 2 tables, one with a Master set (eg. Employees) and one with a child set (eg. Dependents) and you're wanting to get rid of all the rows of data in the Dependents table that cannot key up with any rows in the Master table.
delete from Dependents where EmpID in (
select d.EmpID from Employees e
right join Dependents d on e.EmpID = d.EmpID
where e.EmpID is null)
The point to notice here is that you're just collecting an 'array' of EmpIDs from the join first, the using that set of EmpIDs to do a Deletion operation on the Dependents table.
In SQLite, the only thing that work is something similar to beauXjames' answer.
It seems to come down to this
DELETE FROM table1 WHERE table1.col1 IN (SOME TEMPORARY TABLE);
and that some temporary table can be crated by SELECT and JOIN your two table which you can filter this temporary table based on the condition that you want to delete the records in Table1.
The simpler way is:
DELETE TableA
FROM TableB
WHERE TableA.ID = TableB.ID
DELETE FROM table1
where id IN
(SELECT id FROM table2..INNER JOIN..INNER JOIN WHERE etc)
Minimize use of DML queries with Joins. You should be able to do most of all DML queries with subqueries like above.
In general, joins should only be used when you need to SELECT or GROUP by columns in 2 or more tables. If you're only touching multiple tables to define a population, use subqueries. For DELETE queries, use correlated subquery.
You can run this query:
DELETE FROM TableA
FROM
TableA a, TableB b
WHERE
a.Bid=b.Bid
AND
[my filter condition]