SELECT (CASE WHEN T.ID = ( SELECT cte.REFERENCE FROM trans cte WHERE T.ID
= CTE.PARENT_ID) THEN cte.REFERENCE ELSE null END) AS name
FROM trans T
Example: I am picking one transaction value as an example. In trans table whose ID=1 then in the same table I need to look for PARENT_ID=1.
when I look for parent_ID=1 then it's ID value will be different.
This is not ID=Parent_ID.
once I look for parent_ID=1 then print its corresponding reference value as name.
I tried above sql statement in oracle, but it didn't work. Could you please let me know, how to write this statement in case statement.
Instead of a subquery, why not try a self-join?
SELECT CASE
WHEN nvl(t1.id,-1) = nvl(t2.reference, -1) THEN t2.reference
ELSE 1
END AS number_col
FROM trans t LEFT JOIN trans t2 ON (t.id = t2.parent_id);
You can also try it as a subquery without a case statement
SELECT t.id,
NVL ((SELECT t2.reference
FROM trans t2
WHERE t.id = t2.parent_id AND t.id = t2.reference AND ROWNUM = 1),
1) AS number_val
FROM trans t
I want to update a column of a table1 but I should update only records where conditions are true in another table
something like this, but I don't know how to implement this purpose in Oracle SQL
update table1
join table2 on table1.msg_id = table2.id
set table1.index = table1.index-1
where table1.index > 10 and table2.type = 'myType'
I would write this as an exists subquery in any database:
update table1 t1
set index = t1.index - 1
where table1.index > 10 and
exists (select 1
from table2
where t2.id = t1.msg_id and
t2.type = 'myType'
);
The join sort of implies that you are going to use data from table2 in the update of table1. Instead, you simply want to change a value in a row when a particular condition is met.
Oracle does not support this syntax (sigh).
For your use case, you could use a not exists condition with a correlated subquery instead:
update table1
set table1.index = table1.index - 1
where
table1.index > 10
and exists (
select 1 from table2 where table1.msg_id = table2.id and table2.type = 'mytype'
)
Note: make your live easier, do not use index for a column name. This is a reserved work in pretty much all RDBMS.
I have a table (table1) of names and their frequencies
Name-----Frequency
Mike-------0.56
Fred-------0.30
Nancy------0.14
and a Cartesian product (table2) where the names are paired in two columns and a third column where I would like to sum the frequencies from table1 by matching the names in the first two columns back to table1.
Name1-------Name2------sum
Mike--------Fred
Mike--------Nancy
Fred--------Nancy
I want to update the sum column of table2 using the frequencies in table 1 with a subquery in the update for the matching names (Or so this is how I imagine I need to do it). If there is a better way please let me know.
I have:
UPDATE table2
SET sum = (SELECT dbo.table1.Frequency WHERE Name1 = dbo.table1.Name) +
(SELECT dbo.table1.Frequency WHERE Name2 = dbo.table1.Name)
FROM table1
I get a table full of NULLs instead of the frequency sums.
Am I going about this the right way? Am I totally missing how to do this and there is a better way to do it?
Try updating from a join like this:
update a
set a.sum=isnull(b.frequency,0)+isnull(c.frequency,0)
from table2 a
left join table1 b on a.name1=b.name
left join table1 c on a.name2=c.name
Your method is fine. If all names match:
UPDATE t2
SET sum = (SELECT f.frequency FROM dbo.table1.Frequency f WHERE t2.Name1 = f.Name) +
(SELECT f.frequency FROM dbo.table1.Frequency f WHERE t2.Name2 = f.Name)
FROM table2 t2;
If they don't, then use isnull() (or coalesce(), but isnull() is more efficient):
UPDATE t2
SET sum = isnull( (SELECT f.frequency FROM dbo.table1.Frequency f WHERE t2.Name1 = f.Name), 0) +
isnull( (SELECT f.frequency FROM dbo.table1.Frequency f WHERE t2.Name2 = f.Name), 0)
FROM table2 t2;
I want to update a column in a table making a join on other table e.g.:
UPDATE table1 a
INNER JOIN table2 b ON a.commonfield = b.[common field]
SET a.CalculatedColumn= b.[Calculated Column]
WHERE
b.[common field]= a.commonfield
AND a.BatchNO = '110'
But it is complaining :
Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'a'.
What is wrong here?
You don't quite have SQL Server's proprietary UPDATE FROM syntax down. Also not sure why you needed to join on the CommonField and also filter on it afterward. Try this:
UPDATE t1
SET t1.CalculatedColumn = t2.[Calculated Column]
FROM dbo.Table1 AS t1
INNER JOIN dbo.Table2 AS t2
ON t1.CommonField = t2.[Common Field]
WHERE t1.BatchNo = '110';
If you're doing something silly - like constantly trying to set the value of one column to the aggregate of another column (which violates the principle of avoiding storing redundant data), you can use a CTE (common table expression) - see here and here for more details:
;WITH t2 AS
(
SELECT [key], CalculatedColumn = SUM(some_column)
FROM dbo.table2
GROUP BY [key]
)
UPDATE t1
SET t1.CalculatedColumn = t2.CalculatedColumn
FROM dbo.table1 AS t1
INNER JOIN t2
ON t1.[key] = t2.[key];
The reason this is silly, is that you're going to have to re-run this entire update every single time any row in table2 changes. A SUM is something you can always calculate at runtime and, in doing so, never have to worry that the result is stale.
Try it like this:
UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a INNER JOIN table2 b ON a.commonfield = b.[common field]
WHERE a.BatchNO = '110'
Answer given above by Aaron is perfect:
UPDATE a
SET a.CalculatedColumn = b.[Calculated Column]
FROM Table1 AS a
INNER JOIN Table2 AS b
ON a.CommonField = b.[Common Field]
WHERE a.BatchNo = '110';
Just want to add why this problem occurs in SQL Server when we try to use alias of a table while updating that table, below mention syntax will always give error:
update tableName t
set t.name = 'books new'
where t.id = 1
case can be any if you are updating a single table or updating while using join.
Although above query will work fine in PL/SQL but not in SQL Server.
Correct way to update a table while using table alias in SQL Server is:
update t
set t.name = 'books new'
from tableName t
where t.id = 1
Hope it will help everybody why error came here.
MERGE table1 T
USING table2 S
ON T.CommonField = S."Common Field"
AND T.BatchNo = '110'
WHEN MATCHED THEN
UPDATE
SET CalculatedColumn = S."Calculated Column";
UPDATE mytable
SET myfield = CASE other_field
WHEN 1 THEN 'value'
WHEN 2 THEN 'value'
WHEN 3 THEN 'value'
END
From mytable
Join otherTable on otherTable.id = mytable.id
Where othertable.somecolumn = '1234'
More alternatives here.
Seems like SQL Server 2012 can handle the old update syntax of Teradata too:
UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b
WHERE
b.[common field]= a.commonfield
AND a.BatchNO = '110'
If I remember correctly, 2008R2 was giving error when I tried similar query.
I find it useful to turn an UPDATE into a SELECT to get the rows I want to update as a test before updating. If I can select the exact rows I want, I can update just those rows I want to update.
DECLARE #expense_report_id AS INT
SET #expense_report_id = 1027
--UPDATE expense_report_detail_distribution
--SET service_bill_id = 9
SELECT *
FROM expense_report_detail_distribution erdd
INNER JOIN expense_report_detail erd
INNER JOIN expense_report er
ON er.expense_report_id = erd.expense_report_id
ON erdd.expense_report_detail_id = erd.expense_report_detail_id
WHERE er.expense_report_id = #expense_report_id
Another approach would be to use MERGE
;WITH cteTable1(CalculatedColumn, CommonField)
AS
(
select CalculatedColumn, CommonField from Table1 Where BatchNo = '110'
)
MERGE cteTable1 AS target
USING (select "Calculated Column", "Common Field" FROM dbo.Table2) AS source ("Calculated Column", "Common Field")
ON (target.CommonField = source."Common Field")
WHEN MATCHED THEN
UPDATE SET target.CalculatedColumn = source."Calculated Column";
-Merge is part of the SQL Standard
-Also I'm pretty sure inner join updates are non deterministic..
Similar question here where the answer talks about that
http://ask.sqlservercentral.com/questions/19089/updating-two-tables-using-single-query.html
I think, this is what you are looking for.
UPDATE
Table1
SET
Table1.columeName =T1.columeName * T2.columeName
FROM
Table1 T1
INNER JOIN Table2 T2
ON T1.columeName = T2.columeName;
I had the same issue.. and you don't need to add a physical column.. cuz now you will have to maintain it..
what you can do is add a generic column in the select query:
EX:
select tb1.col1, tb1.col2, tb1.col3 ,
(
select 'Match' from table2 as tbl2
where tbl1.col1 = tbl2.col1 and tab1.col2 = tbl2.col2
)
from myTable as tbl1
Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.
--update clients table cell field from custom table containing mobile numbers
update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m
on c.Last_Name + c.First_Name = m.Name
Those who are using MYSQL
UPDATE table1 INNER JOIN table2 ON table2.id = table1.id SET table1.status = 0 WHERE table1.column = 20
Try:
UPDATE table1
SET CalculatedColumn = ( SELECT [Calculated Column]
FROM table2
WHERE table1.commonfield = [common field])
WHERE BatchNO = '110'
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