SQL Server Update Group by

Gerardo Abdo picture Gerardo Abdo · May 18, 2010 · Viewed 80.3k times · Source

I'm trying to execute this on MS-SQL but returns me an error just at the Group by line

update #temp
Set Dos=Count(1)
From Temp_Table2010 s
where Id=s.Total and s.total in (Select Id from #temp)
group by s.Total

Do anyone knows how can I solve this problem having good performance.

Answer

Code Magician picture Code Magician · Aug 8, 2011

Try

;with counts 
AS 
( 
    SELECT total, COUNT(*) as dos
    FROM temp_table2010 
    WHERE total in (select id from #temp)
)
UPDATE T 
SET dos=counts.dos
FROM #temp T 
INNER JOIN counts 
    ON t.id = counts.total