根据同一查询中返回的数据限制查询结果?

时间:2016-04-19 17:44:45

标签: sql oracle

如果这是一个简单的解决方案,请提前道歉但由于我不知道该怎么称呼这个我试图搜索它没有任何运气。

给出以下示例数据:

ID, QUANTITY, Date
1,2,01-APR-16
1,1,02-APR-16
1,0,03-APR-16
1,1,04-APR-16
1,0,05-APR-16
1,1,06-APR-16
1,0,07-APR-16

我希望查询返回商品的ID以及数量等于零的相应日期,但仅当有更晚的日期时,数量大于零。所以在上面的例子中,select会返回

1,03-APR-16
1,05-APR-16

我学习并从这个网站学到了很多,但我不知道如何完成这个。我知道如何进行基本选择以及如何使用子查询,但在这种情况下,我似乎需要将结果从一行传递给另一行的子查询?感谢您的任何指导,并再次抱歉成为新手。此外,如何以表格格式显示样本表的快速链接将会很有帮助,高级帮助并不表明我可能会在错误的位置查找。谢谢。

3 个答案:

答案 0 :(得分:1)

假设您的表名为t。我更改了列名" date"到" dt" - 不要使用保留的Oracle单词作为列名。

with a as (select id, max(dt) max_dt from t where quantity > 0 group by id)
select id, dt from t join a using (id) where quantity = 0 and t.dt < a.max_dt

ADDED:OP在评论中要求提供额外条件(如下)。这将回答该额外请求。

OP(是的,Mobilemike,就是你!):这个想法是一样的。通过一些练习,您将能够自己完成。注意:仅当最旧的记录的值为0时,我才会删除数量为0的记录(如果不是该ID的绝对最旧记录,我不会删除最旧的记录,数量为零

祝你好运!

with a as (select id, max(dt) max_dt from t where quantity > 0 group by id),
     b as (select id, min(dt) min_dt group by id)
select id, dt from t join a using (id) join b using (id)
where quantity = 0 and t.dt < a.max_dt and t.dt != b.min_dt

答案 1 :(得分:0)

使用子查询而不是临时表的另一种解决方案可能看起来像

select t1.id, t1.dt from t t1, (select id, max(dt) max_dt from t where quantity>0 group by id)  t2
where  t1.id=t2.id and t1.dt < t2.max_dt and t1.quantity =0

我也改变了列名以匹配mathguy给出的名称。

更新:我已将查询更改为帐户ID。

答案 2 :(得分:0)

您可以使用分析来解决此问题,只需在桌面上进行一次阅读:

with t as
(
  select 1 id, 2 QUANTITY, date'2016-04-01' dt from dual union all
  select 1 , 1 , date'2016-04-02' from dual union all
  select 1 , 0 , date'2016-04-03' from dual union all
  select 1 , 1 , date'2016-04-04' from dual union all
  select 1 , 0 , date'2016-04-05' from dual union all
  select 1 , 1 , date'2016-04-06' from dual union all
  select 1 , 0 , date'2016-04-07' from dual
)

select id, quantity, dt from (
  select id, quantity, t.dt, max( quantity ) over ( partition by id order by dt rows between current row and unbounded following ) nxt_qt
  from t
)
where quantity = 0 and nxt_qt > 0
order by 1, 3
相关问题