【问题标题】:Selecting maximum value for a column with contraint为具有约束的列选择最大值
【发布时间】:2011-09-12 02:17:57
【问题描述】:

表格如下

公司,垂直,计数

对于每家公司,我想获得基于具有最高计数的特定垂直的计数总和

公司垂直计数 IBM 财务 10 IBM 研发 5 IBM 公关 2

我想得到以下输出

IBM 财务 17

【问题讨论】:

  • 您的问题不一致。 “我想获得基于具有最高计数的特定垂直的计数总和”似乎你想要财务 = 10,但你说你想要财务 = 17。你想要垂直还是公司?

标签: sql


【解决方案1】:

这是"How to get the MAX row"问题的一个转折点(DBA.SE链接)

  1. 通过简单的聚合获得每个公司的总垂直度和最高垂直度
  2. 使用这些来识别源表中的行

类似的东西,未经测试

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,因为我们不知道平台

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

        【解决方案4】:

        自联接应该这样做。

        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),而不必担心交叉连接。

        【讨论】:

        • 不会给出正确的输出:这如何提取财务行?
        • 好吧,counts=(select max(counts) from table) 恰好在 vertical='Finance' 时,因此我上面的查询产生的行将是 'IBM','Finance',17。
        • 啊,我以为我提到了“如果有不止一家公司”
        猜你喜欢
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        • 2014-12-01
        • 2023-03-25
        • 1970-01-01
        • 2011-02-20
        • 2018-12-16
        相关资源
        最近更新 更多