我试图从下表中检索基于条件的特定行
+----+--------------+------+
| ID | UPDATED_DATE | TYPE |
+----+--------------+------+
| 1 | 01/13 | P |
| 1 | 02/13 | P |
| 1 | 03/13 | P |
| 2 | 01/14 | P |
| 2 | 02/14 | W |
| 2 | 03/14 | P |
| 2 | 04/14 | W |
| 2 | 05/14 | P |
| 2 | 06/14 | P |
+----+--------------+------+
Expected rows:
+----+--------------+------+
| ID | UPDATED_DATE | TYPe |
+----+--------------+------+
| 1 | 01/13 | P |
| 2 | 05/14 | P |
+----+--------------+------+
条件:
如果ID的任何行中都存在类型“ W”,则检索“ W”之后的下一个出现的“ P”。如果没有,则检索第一个出现的“ P”。如果每个ID都有两个“ W”,则在最新的“ W”之后获取“ P”
如果我通过ID,我就能够成功获得所需的行。但是我想为整个表运行并获取必要的行。
SELECT
CASE
WHEN (
SELECT
MAX(UPDATED_DATE)
FROM
TABLE_NAME
WHERE
ID = '1'
AND TYPE = 'W'
) IS NULL THEN
(
SELECT
MIN(UPDATED_DATE)
FROM
TABLE_NAME
WHERE
ID = '1'
)
ELSE
(
SELECT
MIN(UPDATED_DATE)
FROM
TABLE_NAME
WHERE
ID = '1'
AND UPDATED_DATE > (
SELECT
MAX(UPDATED_DATE)
FROM
TABLE_NAME
WHERE
ID = '1'
AND TYPE = 'W'
)
)
END
FROM
dual;
答案 0 :(得分:0)
您可以使用窗口功能:
CPXwriteprob