oracle中的复杂select语句

时间:2013-06-14 20:25:20

标签: .net oracle c#-4.0

我有一个表,其中包含Client_ID和Communication_Date,我想在下表中生成。表应该列出上一个和最后一个通信日期。有没有办法为它编写查询?任何帮助将不胜感激。

由于

ORIGINAL TABLE

ID    Client_ID     Communication_date
1     1001          01-05-2013
2     1002          01-05-2013
3     1003          02-05-2013
4     1001          09-05-2013
5     1001          14-05-2013
6     1002          18-05-2013
7     1002          25-05-2013



Requested Table
Client_ID           PreviousCom_Date       LastCom_date
1001                01-05-2013             09-05-2013
1001                09-05-2013             14-05-2013
1002                01-05-2013             18-05-2013
1002                18-05-2013             25-05-2013
1003                02-05-2013             Null or whatever

1 个答案:

答案 0 :(得分:4)

分析LAG功能会为您配对日期。这将配对当前/以前的日期:

SELECT
  Client_ID,
  Communication_Date AS PreviousCom_Date,
  LAG(Communication_Date) OVER (
    PARTITION BY Client_ID
    ORDER BY Communication_Date DESC) AS LastCom_Date
FROM PrevTable;

然后问题是确保只包含“Previous”和“Last”值的行,除非像Client_ID 1003那样,否则源表中只有一行。这可以通过计算Client_ID行并检查(a)客户端只有一行来处理,或者(b)如果客户端有多行,则两个日期必须具有值:

SELECT * FROM (
  SELECT
    Client_ID,
    Communication_Date AS PreviousCom_Date,
    LAG(Communication_Date) OVER (
      PARTITION BY Client_ID
      ORDER BY Communication_Date DESC) AS LastCom_Date,
    COUNT(*) OVER (
      PARTITION BY Client_ID) AS DatePair_Count
  FROM PrevTable
  )
WHERE DatePair_Count = 1
   OR (PreviousCom_Date IS NOT NULL AND LastCom_Date IS NOT NULL)

CREATE TABLE whatever AS上面的查询之前,它将创建新表。

SELECT语句here有一个SQL小提琴。