How to write a GROUP BY SQL query
I have a "Revenue" table which stores the revenue for a Company State combination.
Company int
State char(2)
IsBiggestState bit
TotalRevenue numeric (10,2)
I need to set the IsBiggestState bit to 1 if the TotalRevenue Amount is the largest amount of all the States within a Company.
How can I write the SQL? Since I am dealing with millions of records, efficiency is of concern.
We are on SQL200开发者_如何学JAVA8 R2.
UPDATE A
SET A.IsBiggestState = 1
FROM YourTable A
INNER JOIN (SELECT Company, MAX(TotalRevenue) MaxRevenue FROM YourTable
GROUP BY Company) B
ON A.Company = B.Company AND A.TotalRevenue = B.MaxRevenue
This would address the problem of 2 states having the same TotalRevenue (if that is indeed a problem). It would mark only one of them as the IsBiggestState. I am not entirely sure how the performance compares to other solutions.
UPDATE A
SET A.IsBiggestState = 1
FROM Revenue A
INNER JOIN
(
SELECT
Company
,[State]
,ROW_NUMBER() OVER (PARTITION BY Company ORDER BY TotalRevenue desc) as rownum
FROM Revenue
) B
ON A.Company = B.Company AND A.[State] = B.[State] AND B.rownum = 1
精彩评论