选择一个复合键,其中max(column_value)

时间:2014-01-20 16:45:24

标签: sql db2 ibm-midrange aggregation

说我有以下内容:

  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

我的真实例子有点复杂,我的意思是没有一个,但有三个子部分(如复合键)。所以我需要确定part夫妻subpart1subpart2subpart3 ...

的每个部分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

作为数据库,我使用db2作为as400,但欢迎使用任何示例。

我尝试执行以下操作,但这不起作用:

{{1}}

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

我认为DB2 for AS400不支持MAX OVER,即窗口化聚合函数?

然后这很容易,否则你需要一个相关的子查询:

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

答案 2 :(得分: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