简体   繁体   English

从表中选择并正确绑定在DB2 / Oracle列上

[英]Select from a table and bind correctly on the columns DB2/Oracle

I have a scenario where I have to select rows from a table and given the requirements, I cannot come up with a sql statement where it could retrieve the rows correctly. 我有一种情况,我必须从表中选择行并给出要求,但我无法提出一条sql语句来正确检索行。

ID  EFFDT        STATUS
1   2001-01-01   A
1   2002-01-01   A
1   2003-01-01   B
1   2004-01-01   B
1   2005-01-01   A
1   2006-01-01   B

I would like to grab all the rows which were not changed at the point of time and get their mininum effective date. 我想获取所有在时间点上未更改的行,并获取其最小有效日期。

I tried something like: 我尝试了类似的东西:

Select e.* 
from employee a 
where e.effdt = (Select min(b.effdt) 
                 from employee b 
                  where e.id= b.id 
                 and e.status= b.status)

It returns two rows: 它返回两行:

ID  EFFDT       STATUS
1   2001-01-01  A    
1   2003-01-01  B

Expected output : 预期产量:

ID   EFFDT        STATUS
1    2001-01-01   A
1    2003-01-01   B
1    2005-01-01   A
1    2006-01-01   B

I need the minimum effective dated row before a status was changed for the same employee multiple times. 在多次更改同一员工的状态之前,我需要最少有效日期的行。

Any help would be really appreciated. 任何帮助将非常感激。 Thanks. 谢谢。

Try this: 尝试这个:

SELECT id, effdt, status
FROM (
  SELECT e.*,
       CASE WHEN id <> @last_id THEN 1
            WHEN status <> @last_status THEN 1
            ELSE 0
       END take_this_row,
       @last_id := id last_id,
       @last_status := status
  FROM employee e
  cross join (
    SELECT @last_id := -111,
           @last_status := 'XXX'
  ) init_var
  ORDER BY id, effdt
) q
WHERE take_this_row = 1

demo --> http://www.sqlfiddle.com/#!2/dec99c/7 演示-> http://www.sqlfiddle.com/#!2/dec99c/7


EDIT 编辑

A query for Oracle: 查询Oracle:

SELECT id, effdt, status
FROM (
  SELECT e.*,
       CASE lag( status ) over (partition by id order by effdt )
            WHEN status THEN 0
            ELSE 1
       END take_this_row
  FROM employee e
)
WHERE take_this_row = 1
ORDER BY id, effdt

Demo --> http://www.sqlfiddle.com/#!4/1d27f/5 演示-> http://www.sqlfiddle.com/#!4/1d27f/5



This query will probaby run also on DB2, unfortunately I have no DB2 installed on my PC and cannot test it. 该查询可能也会在DB2上运行,很不幸,我的PC上没有安装DB2,因此无法对其进行测试。
I've found here: https://www.ibm.com/developerworks/community/blogs/dbtrue/entry/lag_lead_first_value_last_value_totally_new_in_db21?lang=en 我在这里找到: https : //www.ibm.com/developerworks/community/blogs/dbtrue/entry/lag_lead_first_value_last_value_totally_new_in_db21?lang=en
that in DB2 9.7 they have implemented analytic functions LAG, LEAD etc (in their terminology "OLAP functions"), therefore this query should work on DB2. 在DB2 9.7中,他们已经实现了分析功能LAG,LEAD等(用其术语“ OLAP函数”),因此该查询应该在DB2上有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM