2011-06-09 26 views
2

表列選擇最大值如下與contraint

 
Company, Vertical, Counts 

對於每個公司我想獲得具有最高計數

 
Company  Vertical    Counts 
IBM   Finance    10 
IBM   R&D     5 
IBM   PR     2 

我計數的基於特定垂直SUM想獲得以下輸出

 
IBM  Finance 17 
+2

你的問題是不一致的。 「我想根據具有最高計數的特定垂直計算得出計數的總和」似乎你想要金融= 10,但是你後來說你想要金融= 17。你想要垂直還是公司? – 2011-06-09 22:27:03

回答

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,你也可以使用(超過()作爲TOTAL_COUNT如SUM(計數)),而不必擔心交叉連接的窗口功能。

+0

不會給出正確的輸出:這是如何提取財務行? – gbn 2011-06-11 07:49:37

+0

嗯,計數=(從表中選擇最大(計數))正好在vertical ='Finance'時,因此我上面查詢生成的行將是'IBM','Finance',17。 – 2011-06-13 14:39:02

+0

啊,我以爲我提到過「如果有多家公司」 – gbn 2011-06-13 14:50:45

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,因爲我們不知道平臺

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 
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 
相關問題