Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Update with group by

 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.

like image 229
Chen Lu Avatar asked Sep 09 '12 22:09

Chen Lu


People also ask

Can we use GROUP BY with update in SQL?

Can we use GROUP BY clause in an UPDATE statement? Then No.

Can the GROUP BY clause be used in an update statement?

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.

Can we use SELECT * with GROUP BY?

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.

Can we use update and SELECT together?

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.


1 Answers

  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

like image 95
Gonzalo.- Avatar answered Oct 02 '22 17:10

Gonzalo.-