SQL - 选择最小行

时间:2012-03-19 14:47:51

标签: sql select greatest-n-per-group

我如何获得这些线条(相同的线条具有最小的操作,并且它不总是2):

enter image description here

从这个?

enter image description here

这是我的选择:

select SCR.order_number, SCR.product_code, REL.operation, REL.quantity
from scrDATA as SCR INNER JOIN 
     relBDE as REL ON SCR.order_number = REL.order_number

我需要为order_number和product_code计算一个部分(例如order_number FA36001607为1500件,order_number FP7201127为5件。

3 个答案:

答案 0 :(得分:1)

似乎这样可行:

select SCR.order_number, SCR.product_code, MIN(REL.operation), REL.quantity
from scrDATA as SCR INNER JOIN 
     relBDE as REL ON SCR.order_number = REL.order_number
GROUP BY SCR.order_number, SCR.product_code, REL.quantity

答案 1 :(得分:1)

认为这是您需要的查询:

select SCR.order_number, SCR.product_code, REL.operation, REL.quantity
from scrDATA as SCR 
INNER JOIN relBDE as REL ON SCR.order_number = REL.order_number
where REL.operation = 
    (select MIN(REL.operation)
    from scrDATA as SCR 
    INNER JOIN relBDE as REL ON SCR.order_number = REL.order_number)

答案 2 :(得分:1)

类似的东西:

select SCR.order_number, SCR.product_code, REL.operation, SUM(REL.quantity)
FROM scrDATA as SCR
INNER JOIN relBDE as REL ON SCR.order_number = REL.order_number,
( SELECT SCR2.order_number, MIN(REL2.operation) AS operation
                 FROM scrDATA as SCR2
                 INNER JOIN relBDE as REL2 ON SCR2.order_number = REL2.order_number
                 GROUP BY SCR2.order_number) AS SCR_OP 
WHERE SCR.order_number = SCR_OP.order_number 
  AND SCR.operation = SCR_OP.operation
GROUP BY SCR.order_number, SCR.product_code, REL.operation