我有一张表可能有几十万行。每一行代表一个特定申请人在人口普查区内提供资金的申请。如果我只有几百行,我可以使用以下内容为其人口普查区块中的每个应用程序分配一个等级:
SELECT art1.CFA_Plus, art1.Census_Block_ID,
(SELECT count(*) + 1
FROM AppReferenceTable art2
WHERE art2.State_Cost_Per_Unit < art1.State_Cost_Per_Unit AND
art2.Census_Block_ID = art1.Census_Block_ID) AS Rank_In_Block
FROM AppReferenceTable AS art1;
这可以很好地按照人口普查区块中的单位成本对每个应用程序进行排名。但它在我的测试表上窒息,它有大约60,000行。有没有更好的办法?或者,我做错了什么?
谢谢!
答案 0 :(得分:0)
想出来 - 将表连接到自己就可以了。
SELECT art1.Census_Block_ID, art1.CFA_Plus, art1.State_Cost_Per_unit, COUNT(*) As Rank
FROM appreferencetable as art1
LEFT JOIN appreferencetable as art2
ON art1.Census_Block_ID = art2.Census_Block_ID AND art2.State_Cost_Per_Unit <= art1.State_Cost_Per_unit
GROUP BY art1.Census_Block_ID, art1.CFA_Plus, art1.State_cost_per_unit