2014-01-20 47 views
0

說我有以下幾點:選擇複合鍵,其中,max(COLUMN_VALUE)

PART  SUBPART QUANTITY 
    -------- -------- ----------- 
    01  02     2 
    01  03     3 
    01  04     4 
    01  06     3 
    02  05     7 
    02  06     6 
    03  07     6 
    04  08    10 
    04  09    11 
... 

對於每個part我需要的最大數量來識別subpart

我真正的例子是有點複雜,我的意思是沒有一個,但3個子部分列(如複合鍵)。所以,我需要找出part各部分的情侶subpart1subpart2subpart3 ...

由於數據庫中,我使用DB2 AS400,但任何例子是值得歡迎的。

我試着做以下,但是這並不工作:

with T (PART, SUBPART1, SUBPART2, SUBPART3, SQ) AS 
     (SELECT PART, SUBPART1, SUBPART2, SUBPART3, SUM(QUANTITY) 
     FROM MYTABLE 
     GROUP BY PART, SUBPART1, SUBPART2, SUBPART3)  
select PART, SUBPART1, SUBPART2, SUBPART3 
WHERE SQ = max(SQ) 
from T 
group by PART 
+0

db2是否允許'ROW_NUMBER()OVER(PARTITION BY part,subpart1,subpart2,subpart3 ORDER BY quantity DESC)AS part_quantity_rank'? – MatBailie

+0

根據http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fsqlp%2Frbafyolap.htm – serhio

+0

,我可以假設是肯定的,是的,它支持ROW_NUMBER(),它是如果你不想在平局的情況下報告多條記錄,這通常是一個不錯的選擇。 – WarrenT

回答

3

「因爲我需要一個具有最大數量的子部分的每個部分。」這個怎麼樣?

select t.* 
from mytable t join 
    (select part, max(quantity) as maxq 
     from t 
     group by part 
    ) m 
    on m.part = t.part and m.maxq = t.quantity; 
0

我認爲DB2 for AS400不支持MAX OVER,即Windowed Aggregate Functions?

然後,它會很容易,否則你需要一個相關子查詢:

with T (PART, SUBPART1, SUBPART2, SUBPART3, SQ) AS 
     (SELECT PART, SUBPART1, SUBPART2, SUBPART3, SUM(QUANTITY) 
     FROM MYTABLE 
     GROUP BY PART, SUBPART1, SUBPART2, SUBPART3)  
select PART, SUBPART1, SUBPART2, SUBPART3 
from T as t1 
WHERE SQ = 
    (select max(SQ) from T as t2 
    where t1.PART = t2.PART) 

編輯:

這是使用窗式聚合函數

with T (PART, SUBPART1, SUBPART2, SUBPART3, SQ, MAXSQ) AS 
     (SELECT PART, SUBPART1, SUBPART2, SUBPART3, SUM(QUANTITY), 
      SUM(SUM(QUANTITY)) OVER (PARTITION BY PART) 
     FROM MYTABLE 
     GROUP BY PART, SUBPART1, SUBPART2, SUBPART3)  
select PART, SUBPART1, SUBPART2, SUBPART3 
WHERE SQ = MAXSQ 
from T 

但是這個版本的DB2版本似乎只支持排名:

with T (PART, SUBPART1, SUBPART2, SUBPART3, SQ, rnk) AS 
     (SELECT PART, SUBPART1, SUBPART2, SUBPART3, SUM(QUANTITY), 
      RANK() OVER (PARTITION BY PART ORDER BY SUM(QUANTITY) DESC) 
     FROM MYTABLE 
     GROUP BY PART, SUBPART1, SUBPART2, SUBPART3)  
select PART, SUBPART1, SUBPART2, SUBPART3 
WHERE rnk = 1 
from T 
+0

根據http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fsqlp%2Frbafyolap.htm,它應該支持它 – serhio

0

「對於每個零件,我需要確定具有最大數量的subpart」。

SELECT part, subpart 
FROM table t1 
RIGHT JOIN(
SELECT part, subpart, MAX(quantity) 
FROM table 
GROUP BY part, subpart) t2 ON t1.part=t2.part AND t1.subpart=t2.subpart 

在您的示例數據subpart似乎不同,但你沒有說這事,所以我猜subpart不是每個part(有可能是subpart取值01獨特很多部分)

+0

子部分不明顯(可以是2部分) – serhio