insert into tableA (column1)
select min(tableC.column1)
from tableB
inner join tableC on (tableC.coumn2 = tableB.column1
and tableB.column2 = tableA.column2)
group by tableA.column2
How would I change the above to a update with group by instead of insert with group by based on the criteria tableB.column2 = tableA.column2
?
Note that I am using SQL SERVER 2008.
Can we use GROUP BY clause in an UPDATE statement? Then No.
The UPDATE statement does not support GROUP BY, see the documentation. If you're trying to update t1 with the corresponding row from t2, you'd want to use the WHERE clause something like this: UPDATE table t1 SET column1=t2.
You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row.
The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.
Update A set Column1 = minC
from (select Ab.Column2, min(C.Column1) as minC
from A Ab
inner join B on Ab.Column2 = B.Column2
inner join C on C.column2 = B.Column2 --No need to add again the A.col2 = B.col2
group by Ab.Column2) Grouped where A.Column2 = Grouped.Column2
Is this what you want?
This will get for each columnA the C.Column1
min value, and will update it in A.Column1
(that's where you were inserting before), based on condition A.Column2 = Grouped.Column2
.
here is a SQL-Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With