2014-09-28 240 views
0

依賴於第一組的結果,選擇值,我得到了以下數據庫表:多GROUP BY和BY

combination_id | weight | group | std 
------------------------------------------------- 
    1   | 50  | 3  | 7 
    2   | 30  | 3  | 19 
    3   | 30  | 3  | 19 
    4   | 25  | 4  | 7 

I組由列條目STD和總結值

SELECT SUM(weight) as weight_sum, group, std FROM weight_table 
WHERE combination_id IN (1, 2, 3) 
GROUP BY group, std 
ORDER BY weight_sum DESC; 

結果看起來是這樣的:

重量
weight | group | std 
----------------------------------------------- 
    60  | 3  | 19 
    50  | 3  | 7 
    25  | 4  | 7 

現在我想要做的第二GROUP BY,但僅在列,總結在重量列。結果中的std列的值應該是最後一個查詢中權重最高且分組相同的條目的std列的值。 因此,對於組我想STD要選擇19,爲最高重量爲組:

weight | group | std 
----------------------------------------------- 
    110  | 3  | 19 
    25  | 4  | 7 

我怎樣才能做到這一點? 我使用SQLite 3

回答

1

我想你想要這樣的:

SELECT SUM(weight) as weight_sum, group, max(std) as std FROM weight_table 
WHERE combination_id IN (1, 2, 3) 
GROUP BY group 
ORDER BY weight_sum DESC; 

換句話說,不要認爲這是「多重分組依據」。把它看作是一個單一的聚合,你可以同時得到權重的總和和最大值std

編輯:

我似乎誤解了這個問題。這在SQL lite中有點痛苦。以下是一種方法:

with w as (
     SELECT SUM(weight) as weight_sum, group, std 
     FROM weight_table 
     WHERE combination_id IN (1, 2, 3) 
     GROUP BY group, std 
    ), 
    wmax as (
     SELECT group, MAX(weight_sum) as maxws 
     FROM w 
     GROUP BY gruop 
    ) 
select w.group, sum(w.weight_sum) as weight_sum, 
     max(case when w.weight_sum = wmax.weight_sum then std end) as std 
from w left join 
    wmax 
    on w.group = wmax.group 
group by w.group 
order by weight_sum DESC; 
+0

他希望基於最大'weight_sum'的'std',這使得[tag:greatest-n-per-group]最大化,而不是簡單的聚合。 – 2014-09-28 12:35:15

+0

@ Clockwork-Muse。 。 。謝謝。我確定了答案。 – 2014-09-28 13:14:25

+0

謝謝,完美的作品! – uih98hsdfhhs8p 2014-09-28 15:53:44