【发布时间】:2011-09-12 02:17:57
【问题描述】:
表格如下
公司,垂直,计数对于每家公司,我想获得基于具有最高计数的特定垂直的计数总和
公司垂直计数 IBM 财务 10 IBM 研发 5 IBM 公关 2我想得到以下输出
IBM 财务 17【问题讨论】:
-
您的问题不一致。 “我想获得基于具有最高计数的特定垂直的计数总和”似乎你想要财务 = 10,但你说你想要财务 = 17。你想要垂直还是公司?
标签: sql
表格如下
公司,垂直,计数对于每家公司,我想获得基于具有最高计数的特定垂直的计数总和
公司垂直计数 IBM 财务 10 IBM 研发 5 IBM 公关 2我想得到以下输出
IBM 财务 17【问题讨论】:
标签: sql
这是"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,
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
【讨论】:
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_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 () as total_count),而不必担心交叉连接。
【讨论】: