WITH max_date_6 AS
(
SELECT no,
Max(DATE) date_6
FROM TABLE
where status=6
AND no='00000001 001'
GROUP BY no ), max_date_1 AS
(
SELECT no,
max(DATE) date_1
FROM TABLE
WHERE status=1
AND no='00000001 001'
GROUP BY no)
SELECT date_6,
date_1
FROM max_date_6,
max_date_1 where date_6<=date_1
答案 0 :(得分:0)
这里不需要复杂化,只需要两个MAX&#39; s
SELECT Max(case when status = 6 then DATE end) as date_6,
Max(case when status = 1 then DATE end) as date_1
FROM TABLE
where no='00000001 001'
已编辑的版本,现在需要date_1&gt; max(date_6),如果没有date_1&gt;,则返回null。 max(date_6),否则与之前的结果相同。
SELECT Max(case when status = 6 then DATE end) as date_6,
(select Max(DATE)
from TABLE
where status = 1
and no = t1.no
and date > (select max(date) from TABLE
where no = t1.no
and status = 6)) as date_1
FROM TABLE t1
where no = '00000001 001'
答案 1 :(得分:0)
因此,您需要date
的最大status=6
和{<1}}来自之前行的date
。
除非你有一些收集行的顺序,否则这是不可能的。出于这个原因,我添加了列ID(也许你有一些其他键,但隐藏它)。
所以输入数据是:
status=1
查询和结果:
NO TDATE STATUS ID
----------------- ----- ------ --
00000001 001 21223 1 1
00000001 001 21041 1 2
00000001 001 21002 1 3
00000001 001 20943 6 4
00000001 001 20939 6 5
00000001 001 20933 1 6
00000001 001 20943 6 7
答案 2 :(得分:0)
鉴于您的预期数据,听起来好像您希望状态= 1的最小日期,其中该日期大于状态= 6的最大日期。
WITH m6 AS (
SELECT max(tdate) AS max_date_6
FROM mytable
WHERE status = 6
AND no = '00000001 001'
)
SELECT min(m1.tdate) AS max_date_1, m6.max_date_6
FROM mytable m1, m6
WHERE m1.status = 1
AND m1.no = '00000001 001'
AND m1.tdate > m6.max_date_6;
可替换地:
WITH m6 AS (
SELECT no, max(tdate) AS max_date_6
FROM mytable
WHERE status = 6
GROUP BY no
)
SELECT min(m1.tdate) AS max_date_1, m6.max_date_6
FROM mytable m1 INNER JOIN m6
ON m1.no = m6.no
AND m1.tdate > m6.max_date_6
WHERE m1.status = 1
AND m1.no = '00000001 001';