如何使用MAX和其他标准

时间:2012-02-22 05:21:18

标签: sql db2

A)当货物被出售时,表格将在列ID和列表中记录“O”。列TYPE中的“N”: -

SKU      ID  TYPE  NR
-------------------------
HAB1122  O   N     201211

B)当退回货物时,表格将在列ID&中记录“O”。列TYPE中的“R”: -

SKU      ID  TYPE  NR
-------------------------
HAB1122  O   R     201223

情景1

商品已售出&稍后回来。随后出售: -

SKU      ID  TYPE  NR
-------------------------
HAB1122  O   N     201211
HAB1122  O   R     201223
HAB1122  O   N     201245
HAB2233  O   N     201263
HAB3344  O   N     201303
HAB3344  O   R     201341

使用SQL: -

Select SKU, max(NR) 
from tableA
where SKU like ‘HAB%’ and ID = ‘O’
group by SKU

结果: -

SKU       NR
----------------
HAB1122   201245
HAB2233   201263
HAB3344   201341

这是正确的结果,因为我希望追踪所售商品的最后一个NR,无论商品是否已售出或退回。

如果我想追踪仅售出状态的商品的最后一件商品,预期结果应为: -

SKU      NR
---------------
HAB1122  201245
HAB2233  201263

HAB3344不被视为货物退回&不随后出售。

我应该如何更改SQL?

4 个答案:

答案 0 :(得分:2)

试试这个:

select   SKU, max(NR)
from     TABLEA T1
where    SKU like 'HAB%' and ID = 'O'
group by SKU
having   max(NR) <> (select nvl(max(NR), 0)
                     from   TABLEA T2
                     where  T1.SKU = T2.SKU and T2.type = 'R');

这是使用Oracle。您没有指明您的系统,因此having可能无法专门针对您的系统,而是等效的。

答案 1 :(得分:1)

SELECT *
FROM tableA AS T1
WHERE SKU like ‘HAB%’ and ID = ‘O’ AND T1.[TYPE] = 'N'
AND NOT EXISTS (
    SELECT *
    FROM tableA AS T2
    WHERE T2.SKU = T1.SKU
    AND T2.NR > T1.NR
    AND ID = ‘O’
)

结果:

SKU        ID   TYPE NR
---------- ---- ---- -----------
HAB1122    O    N    201245
HAB2233    O    N    201263

通过快速谷歌搜索,DB2似乎支持Window Functions和CTE。我可以说至少对于SQL Server,窗口函数在这种情况下表现更好:

ROW_NUMBER()http://forums.devshed.com/db2-development-114/rownumber-over-169453.html

CTE:http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/samples/clp/s-cte-db2.htm

窗口函数方法:

WITH T AS (
    SELECT T1.*,
           ROW_NUMBER() OVER(PARTITION BY SKU ORDER BY NR DESC) AS RN
    FROM tableA AS T1 
    WHERE ID = ‘O’
)
SELECT T.SKU, T.NR
FROM T 
WHERE RN = 1 AND SKU like ‘HAB%’ AND T1.[TYPE] = 'N';

答案 2 :(得分:0)

Select SKU, max(NR) from tableA where SKU like 'HAB%' and ID = 'O' and TYPE = 'N' group by SKU

答案 3 :(得分:0)

如果您的数据库系统支持排名功能,例如ROW_NUMBER(),您可以尝试以下操作:

WITH ranked AS (
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY SKU ORDER BY NR DESC) AS RNK
  FROM atable
  WHERE SKU LIKE 'HAB%'
    AND ID = 'O'
)
SELECT
  SKU,
  NR
FROM ranked
WHERE TYPE = 'N'
  AND RNK = 1