这里的第一篇文章,但已经多次从这里得到答案 - 虽然我似乎无法找到当前挑战的答案。 此外,SQL对我来说还有3个星期的时间,所以我为之前缺乏知识而道歉。
我有一个表(logfile),我希望从中获取某些实例的第一个和最后一个日期,以便能够测量不同任务(状态)之间的时间。
该表看起来有点像这样:
文章,regdate,status,queue,area
我想在文章级别进行衡量,但每篇文章都可以多次出现在表格中,并且每种状态都可以多次出现。我希望能够获取实例的FIRST(最小(时间))和另一个实例的最后(最大(时间))。
包含数据的表格(A)如下所示:
article | regdate | status | queue | area
--------+----------+--------+-------+-----
1111 | 14/05/14 | 2 | LO2ST | P2
1123 | 14/03/21 | 3 | INLOA | P1
1123 | 14/03/21 | 2 | LO2ST | P2
1123 | 14/03/20 | 3 | INLOA | P1
1111 | 14/04/21 | 2 | LO2ST | P2
现在,我想在每篇文章的状态3中列出最终名单,我想对每篇文章的状态2采取最新的发生。
我试过以下:
SELECT
article,
(select min(regdate) from A where status = 3 and queue = INLOA) as FIRSTLOA,
(select max(regdate) from A where status = 2 and queue = LO2ST) as LAST
FROM A
GROUP BY A
但这只是让我第一次出现表中所有记录的状态3,并且与表中状态2的最后一次出现相同。
如何在文章级别获得给定参数的第一次和最后一次出现?
答案 0 :(得分:0)
第三个选择匹配min和max
的项目SELECT article, regdate, status, queue, area
FROM
(
-- Second find the min and max
SELECT article, regdate, status, queue, area, RN,
MAX(rn) OVER (PARTITION BY status, queue) as MAXRN,
MIN(rn) OVER (PARTITION BY status, queue) as MINRN
ROW_NUMBER() OVER (PARTITION BY status, queue ORDER BY regdate) as RN
FROM
(
-- First make a row_number
SELECT article, regdate, status, queue, area,
ROW_NUMBER() OVER (PARTITION BY status, queue ORDER BY regdate) as RN
) sub1
) sub2
WHERE
-- Third take the items that match min and max
RN = MAXRN OR RN = MINRN
答案 1 :(得分:0)
我认为你想要条件聚合:
SELECT article,
min(case when status = 3 and queue = INLOA then regdate end) as FirstLOA,
min(case when status = 2 and queue = LO2ST then regdate end) as LAST
FROM A
GROUP BY A;