表格如下
Company, Vertical, Counts
对于每个公司,我希望根据具有最高计数的特定垂直来获得计数的总和
Company Vertical Counts IBM Finance 10 IBM R&D 5 IBM PR 2
我想获得以下输出
IBM Finance 17
答案 0 :(得分:1)
自我加入应该这样做。
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,您还可以使用窗口函数(例如sum(count)over()作为total_count),而不必担心交叉连接。
答案 1 :(得分:1)
这是对"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
编辑:这比标准SQL更接近ROW_NUMBER因为我们不知道平台
答案 2 :(得分:0)
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
答案 3 :(得分:0)
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