我有下表:
LOCATION_ID, PERSON_ID, DATE
3, 65, 2016-06-03
7, 23, 2016-10-28
3, 23, 2016-08-05
5, 65, 2016-07-14
我想在PL / SQL中构建一个select查询,以选择每人person_id 最近 location_id的记录。对于上述样本,所需的结果应为:
LOCATION_ID, PERSON_ID, DATE
5, 65, 2016-07-14
7, 23, 2016-10-28
(DATE表示为' YYYY-MM-DD')
谢谢!
答案 0 :(得分:4)
其他提案是正确的,但最简单,最快速的解决方案最有可能在您使用FIRST_VALUE and LAST_VALUE Analytic Functions
时SELECT DISTINCT
FIRST_VALUE(LOCATION_ID) OVER (PARTITION BY PERSON_ID ORDER BY THE_DATE
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LOCATION_ID,
PERSON_ID,
MAX(THE_DATE) OVER (PARTITION BY PERSON_ID) AS LAST_DATE
FROM YOUR_TABLE;
其他人更喜欢
SELECT
MAX(LOCATION_ID) KEEP (DENSE_RANK FIRST ORDER BY DATE) as LOCATION,
PERSON_ID,
MAX(DATE) as LAST_DATE
FROM YOUR_TABLE
GROUP BY PERSON_ID;
也是如此,但我对这个条款并不熟悉。见aggregate_function KEEP
答案 1 :(得分:1)
您可以先按PERSON_ID
对结果进行分组并选择MAX(DATE)
,然后为每个人提取最近的事件。
然后在这两列上连接表格以检索LOCATION_ID
SELECT
YOUR_TABLE.LOCATION_ID,
YOUR_TABLE.PERSON_ID,
YOUR_TABLE.DATE
FROM
(SELECT
PERSON_ID, MAX(DATE) AS max_date
FROM
YOUR_TABLE
GROUP BY
PERSON_ID
) AS t1
LEFT JOIN
YOUR_TABLE
ON
YOUR_TABLE.PERSON_ID = t1.PERSON_ID
AND
YOUR_TABLE.DATE = t1.max_date
顺便说一句,你不应该使用像DATE
这样的保留字来表示列名。
以下是显示它正常工作的小提琴:http://sqlfiddle.com/#!9/efdcb/2
答案 2 :(得分:0)
@quasoft是正确的。处理这些GROUP BY
问题的另一种方法(当你想要返回的列多于你想要分组的列时。在你的情况下,你需要返回location_id,person_id。但是你只需要按person_id分组),是使用analytical functions。
--schema:
CREATE TABLE my_table
(
location_id NUMBER,
person_id NUMBER,
date_ DATE
);
INSERT ALL
INTO my_table
VALUES (3, 65, To_date('2016-06-03', 'YYYY-MM-DD'))
INTO my_table
VALUES (7, 23, To_date('2016-10-28', 'YYYY-MM-DD'))
INTO my_table
VALUES (3, 23, To_date('2016-08-05', 'YYYY-MM-DD'))
INTO my_table
VALUES (5, 65, To_date('2016-07-14', 'YYYY-MM-DD'))
SELECT *
FROM dual;
--query:
WITH ordered
AS (SELECT location_id,
person_id,
date_,
Row_number()
over (
PARTITION BY person_id
ORDER BY date_ DESC) RN
FROM my_table)
SELECT location_id,
person_id,
date_
FROM ordered
WHERE rn = 1;
查询ordered
按日期对每个组的行进行排序。主查询在排序后返回每个组的前1个。因此,在这种情况下,它将返回最后一个(我们按date_desc排序)。
答案 3 :(得分:0)
这可能有用!
SELECT * FROM Your_Table A
JOIN (SELECT PERSON_ID,MAX(DATE) as MaxDate FROM Your_Table
GROUP BY PERSON_ID) B
ON A.PERSON_ID = B.PERSON_ID AND A.DATE = B.MaxDate