How to update table using select statement results in sql server - sql

I am trying to update a tabel where the value of field is equal the result of select statement. I have a table like this:
Type Total#
A 4
B 8
C 1
I want to update the above table based the result of a select statement.
Here is my code:
update MainTable
set [Total#] =
(SELECT count(distinct r.[ID])as Type
FROM dbo.TableA r left join
dbo.TableB a
on r.Post_ID = a.Post_ID
where a.Status is null)
if i run the code as is, it is going to update all rows but i only want to update where Type from select statement is equal the Type from my MainTable. thanks

Give this a try,
UPDATE x
SET x.[Total#] = y.totalCount
FROM MainTable x
INNER JOIN
(
SELECT [Type], COUNT(DISTINCT r.[ID]) totalCount
FROM dbo.TableA r
LEFT JOIN dbo.TableB a
ON r.Post_ID = a.Post_ID
WHERE a.STATUS IS NULL
GROUP BY [Type]
) y ON x.[Type] = y.[Type]
PS: when asking question like this, please add the structure of the table. It helps a lot.

Give an alias to your MainTable and you can use it in the subquery:
update MainTable mt
set [Total#] = (SELECT count(distinct r.[ID]) as Type
FROM dbo.TableA r
left join dbo.TableB a on r.Post_ID = a.Post_ID
where a.Status is null
and a.AType = mt.AType )
where mt.AType = #Value

Related

Redshift: UPDATE statement using a LEFT JOIN returns "table name specified more than once" error

I have an UPDATE statement in Redshift that I'd like to use the LEFT JOIN method to identify records that don't exist in the second table. The statement keeps returning the "table name specified more than once" error. I understand I can use different methods such as NOT IN with a subquery but I'd like to learn how can I adapt this script in PostgreSQL using LEFT JOIN approach. Thank you in advance.
UPDATE A
SET A.column_Name = 'Y'
FROM tbl_A A
LEFT JOIN tbl_B B
ON A.Mathcing_Column_Name = B.Matching_Column_Name
WHERE B.Matching_Column_Name is NULL
Use NOT EXISTS instead:
UPDATE tbl_A A
SET column_Name = 'Y'
WHERE NOT EXISTS (SELECT 1
FROM tbl_B B
WHERE A.Matching_Column_Name = B.Matching_Column_Name
);
Try this. (it's working)
with temp AS
(
SELECT A.* FROM tbl_A A
LEFT JOIN tbl_B B
ON A.Mathcing_Column_Name = B.Matching_Column_Name
WHERE B.Matching_Column_Name is NULL
)
UPDATE tbl_A C SET column_Name = 'Y'
from temp D
where C.id=D.id

Update column in Oracle table with value from another table with duplicates

I am trying to update the column (REPT_IND) from table A to the value in table B where A.ID = B.ID and some conditions in table B.
There are some duplicates in table B, but nonetheless the REPT_IND is the same and I still need the value.
How can I do this on Oracle? Any tips are appreciated thank you!
The Following code has the Error:
ORA-01427: single-row subquery returns more than one row
Code:
UPDATE A
SET REPT_IND= (
SELECT B.REPT_IND
FROM B
INNER JOIN A
ON B.ID = A.ID
where A.ID = B.ID
and B.job_type = 'P'
and B.FT_PT is not null
);
You can try also merge statement:
merge into a
using (
select a.id,max(b.rept_ind) rept_ind
from a left join b on a.id=b.id
where b.job_type = 'p'
and b.ft_pt is not null
) b
on (a.id=b.id)
when matched then update
set a.rept_ind=b.rept_ind;
Or if you do not want to set a.rept_ind to null if there is no relevant rows in b:
merge into a
using (
select b.id, max(b.rept_ind) rept_ind
from b
where
b.job_type = 'p'
and b.ft_pt is not null
group by b.id
) b
on (a.id=b.id)
when matched then update
set a.rept_ind=b.rept_ind;
Consider:
update a
set rept_ind= (
select max(b.rept_ind)
from b
where
a.id = b.id
and b.job_type = 'p'
and b.ft_pt is not null
);
There is no need to join table a again in the subquery - a correlation clause is enough. And you can work around possible duplicates by turning on aggregation, which guarantees that only one row will be returned.
You could also use select distinct instead of select max(...) in the subquery. This is somehow more accurate since it does ensure that the multiple rows have the same rept_ind (it they do not, then you would still get the ORA-01427 error).
Just use a correlated subquery . . . and do not repeat the table reference in the subquery:
UPDATE A
SET REPT_IND = (SELECT B.REPT_IND
FROM B
WHERE B.ID = A.ID AND
B.job_type = 'P' AND
B.FT_PT is not null AND
rownum = 1
);

SQL: Join table a and b then join table c to get the results that are on a but not on c?

i have 3 tables. Table a pk = userid, table b and c fk = userid. On table b RoleID column is equal to Usermanager column from table c but w a new value.
So i joined table a and b with below query
select a.Username, a.Userid, b.Roleid
from NewTable a
join RoleTable b
on a.UserID=b.UserID
where b.RoleID = 2
This results in 502 records.
Table c query is
select *
from OldTable
where UserManager = 1
and Authorized = 1
and Status = 'A'
This results in 500 records.
So I'm trying to join the 2 queries to find the 2 records that are not on table c but are only on table a.
Thanks.
Try this:
select a.Username, a.Userid, b.Roleid
from NewTable a
join RoleTable b
on a.UserID=b.UserID
where
b.RoleID = 2
AND
NOT EXISTS
(select *
from OldTable AS c
where c.UserManager = 1
and
c.Authorized = 1
and
c.Status = 'A'
AND
a.userid = c.userid)
I used the two queries you mentioned you were using and just made the table c query into a WHERE NOT EXISTS subquery. It should provide those 2 results you are looking for.
Something like this should do the trick. You can work out the details for your database.
select fields
from tableA join tableB on something
where whatever
and tableA.someField in
(select someField
from tableA join tableB on something
where whatever
except
select someEquivalentField
from tableC)
The two where whatevers should be the same.
If I understand your question correctly... the following will join Table A and Table C and then find those that dont have corresponding values in Table C
Select * from Table A A
LEFT JOIN Table C C On A.UserId = C.UserId
Where C.UserId is NULL
This is the basic concept.. you need to work on it to get the syntax to fit your motives
You can do this with a Left Join
select subA.*
from (
select a.Username, a.Userid, b.Roleid
from NewTable a
join RoleTable b
on a.UserID=b.UserID
where b.RoleID = 2
) subA
left join (
select userID
from OldTable
where UserManager = 1
and Authorized = 1
and Status = 'A'
) subB
on subA.Userid = subB.UserID
Where subB.userid is null

Select where tuple in statement

I have table with two FK UserProfile_Id and Service_Id. This table contains bit field which value I need to change.
I have two temporary tables:
First table #temp2:
EmailAddress,
UserProfile_Id
Second table #temp:
EmailAddress,
Service_Id
This statement does not work:
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
I know why it does not work, but have no idea how to fix it to work fine.
I need to change bitField for MailSubscription where tuple(UserProfile_Id,Service_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
UPDATE M
SET M.BitField=1
from MailSubscription M
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id
inner join #temp t on M.Service_id=t.ServiceId
and t.EmailAddress=t2.EmailAddress
UPDATE MailSubscription SET BitField=1
FROM #temp2
JOIN #temp on #temp2.EmailAddress=#temp.EmailAddress
WHERE MailSubscription.Service_id = #temp.ServiceId
AND MailSubscription.UserProfile_id = #temp2.UserProfile_Id
You could use a filtering join:
update m
set BitField = 1
from MailSubscription m
join #temp t1
on t1.Service_id = m.Service_id
join #temp2 t2
on t2.UserProfile_Id= m.UserProfile_Id
and t1.EmailAddress = t2.EmailAddress
Another option with EXISTS operator
UPDATE MailSubscription
SET BitField = 1
WHERE EXISTS (
SELECT 1
FROM #temp2 t2 JOIN #temp t ON t2.EmailAddress = t.EmailAddress
WHERE t2.UserProfile_Id = MailSubscription.UserProfile_Id
AND t.Service_Id = MailSubscription.Service_Id
)
I think this should help u find the answer.
Update 'Tablename'
SET Mailsubscription = 1
WHERE concat(UserProfile_Id ,".", Service_Id) IN (
SELECT concat(t.UserProfile_Id , "." , t2,Service_Id)
FROM #temp t INNER JOIN #temp2 t2
ON t2.EmailAddress = t.EmailAddress)
update MailSubscription set
BitField = 1
from MailSubscription as MS
where
exists
(
select *
from #temp2 as T2
inner join #temp as T on T.EmailAddress = T2.EmailAddress
where
T2.UserProfile_Id = MS.UserProfile_Id and
T.Service_Id = MS.Service_Id
)

SQL join with case

How can I modify the join clause with a case clause; for example I want the table to join another column if column1 is null such as:
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON
CASE WHEN MYTABLE.A IS NULL THEN MYTABLE.B = OTHERTABLE.A
ELSE MYTABLE.A IS NOT NULL THEN MYTABLE.A = OTHERTABLE.A
(totally made that up,sorry for syntax errors :))
Try this one:
SELECT *
FROM MyTable M
LEFT JOIN OtherTable O ON(CASE WHEN M.A IS NULL THEN M.B ELSE M.A END) = O.A
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON COALESCE(MYTABLE.A, MYTABLE.B) = OTHERTABLE.A
Just try below code :
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON OTHERTABLE.A = isnull(MYTABLE.A,MYTABLE.B)
You can use isnull() or coalesce() to check the null value.