SQL Oracle ---每月获得最后一条记录

时间:2011-10-28 21:25:28

标签: sql oracle stored-procedures plsql

我有一个包含一些检验数据的表格。每个月都需要检查每种商品。这里的目标是找到每个月的最后一次检查记录。

表检查:

INSPECTION_I -------- INSPECTION_TS

200 --------------------------- 10/20/2011

201 ---------------------------- 10/24/2011

202 ---------------------------- 10/26/2011

表Product_Inspection:

INSPECTION_I ------------------ ASSET_I

200 ------------------------------------ 1000

201 ------------------------------------ 2000

Table Box_Inspection

INSPECTION_I -------- ASSET_I

202 ------------------------ 3000

表产品

ASSET_I ------------ ASSOCIATED_BOX_ASSET_I

1000 3000 ---------------------------

表格框:

ASSET_I ------------ OTHER_STUFF

3000 -------------------- #####

现在在这种情况下我想要的是 201 而不是 200 。我试图做 MAX(to_char(inspection_ts,'mm / yyyy')),但这没有帮助。还有一个问题。出于某种原因,如果产品或盒子在一个月内检查两次或更多次,我会继续购买笛卡尔。我想要的只是每月一次检查,这应该是每个月的最后一次检查。我真的很接近它,但如果有人可以提供帮助,我会非常感激。我能够通过嵌套游标完成它,但我不希望这样。

2 个答案:

答案 0 :(得分:3)

我倾向于使用分析函数来执行此类查询。类似的东西:

with data as
(
    select 1 product_id, 100 inspection_id, to_date('09/04/2011', 'MM/DD/YYYY') inspection_date from dual union all
    select 1 product_id, 101 inspection_id, to_date('09/14/2011', 'MM/DD/YYYY') inspection_date from dual union all
    select 1 product_id, 103 inspection_id, to_date('10/04/2011', 'MM/DD/YYYY') inspection_date from dual union all
    select 1 product_id, 105 inspection_id, to_date('11/01/2011', 'MM/DD/YYYY') inspection_date from dual union all
    select 2 product_id, 102 inspection_id, to_date('09/24/2011', 'MM/DD/YYYY') inspection_date from dual union all
    select 2 product_id, 104 inspection_id, to_date('10/05/2011', 'MM/DD/YYYY') inspection_date from dual
)
select *
from 
(
    select
        product_id,
        inspection_id,
        inspection_date,
        row_number() over (
            partition by
                product_id,
                trunc(inspection_date, 'MM') -- Month
            order by
                inspection_date desc
        ) rn
    from
        data
)
where rn = 1 -- indicates last inspection date of the month for each product

答案 1 :(得分:0)

使用子查询

Select [ColName List]
From TableName a
Where DateTimeColumname 
   = (Select Max(DateTimeColumnName)
      From TableName 
      Where DateTimeColumnName < 1+Last_Day(a.DateTimeColumnName))