需要有关GROUP BY SQL的帮助

时间:2011-09-26 17:09:02

标签: sql tsql sql-server-2008

我有一个“收入”表,用于存储公司州组合的收入。

Company int
State   char(2)
IsBiggestState bit
TotalRevenue numeric (10,2)

如果TotalRevenue Amount是公司内所有州的最大金额,我需要将IsBiggestState位设置为1。

你能帮我写一下SQL吗?由于我正在处理数百万条记录,因此效率值得关注。

我们在SQL2008 R2上。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

这将解决2个州具有相同TotalRevenue的问题(如果这确实是一个问题)。它只会将其中一个标记为IsBiggestState。我不完全确定性能与其他解决方案的比较。

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