困难查询(DB2)

时间:2010-02-08 15:51:12

标签: db2

假设我有一个名为spitems的表,其中包含以下字段:

  • spitemid(独特的钥匙)
  • modifiedon(timestamp)
  • parentId的
  • 许多其他无意义的字段

我想要检索的是每个parentid具有最高修改日的spitem行。

但是,请注意,modifiedon时间戳不是唯一的,因此对于一个父ID,有两个spitemids具有相同的modifiedon时间戳。在这种情况下,我需要列出这两种spitemids中的一种,我不关心哪一种。

所以要明确:我返回的列表应该只包含一次所有的parentids。

5 个答案:

答案 0 :(得分:2)

<强>更新

见面,这是我的镜头:

select * 
from table
join where spitmid in 
  (select max(spitmid) 
   from table
   join 
     (select parentid, max(modifiedon) as d from table group by parentid) inlist
      on table.parentid = inlist.parentid and table.modifiedon = inlist.d
   group by parentid, datemodified
  ) 

旧条目

不确定这在DB2上是否有所不同,这里是sql server。

    select * 
    from table
    join (select parentid, max(modifiedon) as d from table group by parentid) as toplist on 
      table.parentid = toplist.parentid and table.modifiedon = toplist.d

嗯...这将为复制件返回多个...现在无法修复它,必须去参加会议。

答案 1 :(得分:1)

根据您的要求,以下内容可为您提供最新的项目。

SELECT    t1.*
FROM      Table t1
          INNER JOIN (
            SELECT    spitemid = MAX(t1.spitemid)
            FROM      Table t1
                      INNER JOIN (
                        SELECT   parentid, modifiedon = MAX(modifiedon)
                        FROM     Table
                        GROUP BY parentid
                      ) t2 ON t2.parentid = t1.parentid
                              AND t2.modifiedon = t1.modifiedon
            GROUP BY  t1.parentid, t1.modifiedon
          ) t2 ON t2.spitemid = t1.spitemid

答案 2 :(得分:0)

您可以使用两个嵌套子查询来完成此操作。第一个获得每个parentid的最大修改,然后第二个获得每个parentid / modifiedon组的最大spitemid。

SELECT *
FROM spitems
WHERE spitemid IN 
(
    SELECT      parentid, modifiedon, max(spitemid) spitemid
    FROM (
        SELECT      parentid, MAX(modifiedon) modifiedon
        FROM        spitems
        GROUP BY    parentid
    ) A
    GROUP BY parentid, modifiedon
)

答案 3 :(得分:0)

公共表表达式使您有机会在发出最终SELECT之前对行进行编号。

WITH items AS 
(
SELECT spitemid, parentid, modifiedon, 
ROWNUMBER() OVER (PARTITION BY parentid ORDER BY modifiedon DESC) AS rnum
FROM yourTable
)
SELECT spitemid, parentid, modifiedon FROM items WHERE rnum = 1
;

答案 4 :(得分:-3)

SELECT sr.receiving_id, sc.collection_id FROM stock_collection as sc, stock_requisation as srq, stock_receiving as sr WHERE (sc.stock_id = '" & strStockID & "' AND sc.datemm_issued = '" & strMM & "' AND sc.qty_issued >= 0 AND sc.collection_id = srq.requisition_id AND srq.active_status = 'Active') OR (sr.stock_id = '" & strStockID & "' AND sr.datemm_received = '" & strMM & "' AND sr.qty_received >= 0)