表列選擇最大值如下與contraint
Company, Vertical, Counts
對於每個公司我想獲得具有最高計數
Company Vertical Counts IBM Finance 10 IBM R&D 5 IBM PR 2
我計數的基於特定垂直SUM想獲得以下輸出
IBM Finance 17
表列選擇最大值如下與contraint
Company, Vertical, Counts
對於每個公司我想獲得具有最高計數
Company Vertical Counts IBM Finance 10 IBM R&D 5 IBM PR 2
我計數的基於特定垂直SUM想獲得以下輸出
IBM Finance 17
自聯接應該這樣做。
select company, vertical, total_count
from(
select sum(counts) as total_count
from table
)a
cross join table
where counts=(select max(counts) from table);
根據您的RDBMS,你也可以使用(超過()作爲TOTAL_COUNT如SUM(計數)),而不必擔心交叉連接的窗口功能。
這是對的"How to get the MAX row"(DBA.SE鏈接)問題
事情是這樣的,未經檢驗
SELECT
t.Company, t.Vertical, m.CompanyCount
FROM
(--get total and highest vertical per Company
SELECT
COUNT(*) AS CompanyCount,
MAX(Vertical) AS CompanyMaxVertical,
Company
FROM MyTable
GROUP BY Company
) m
JOIN --back to get the row for that company with highest vertical
MyTable t ON m.Company = t.Company AND m.CompanyMaxVertical = t.Vertical
埃德它:這是不是ROW_NUMBER更接近於標準的SQL,因爲我們不知道平臺
select Company,
Vertical,
SumCounts
from (
select Company,
Vertical,
row_number() over(partition by Company order by Counts desc) as rn,
sum(Counts) over(partition by Company) as SumCounts
from YourTable
) as T
where rn = 1
SELECT company,
vertical,
total_sum
FROM (
SELECT Company,
Vertical,
sum(counts) over (partition by null) as total_sum,
rank() over (order by counts desc) as count_rank
FROM the_table
) t
WHERE count_rank = 1
你的問題是不一致的。 「我想根據具有最高計數的特定垂直計算得出計數的總和」似乎你想要金融= 10,但是你後來說你想要金融= 17。你想要垂直還是公司? – 2011-06-09 22:27:03