如何解决根据多个列按日期时间获取最新记录
想知道如何在postgresql中做些什么,我有一张桌子,
AcctNo EntryDate EntryTime Form FormSeq anscode answer
123456 8/14/20 07:05 ORREC 0001 ans1 1245
123456 8/13/20 07:07 ORREC 0001 ans1 1235
123456 8/14/20 07:04 ORREC 0001 ans2 test
123456 8/14/20 07:05 ORREC 0001 ans2 testing
123456 8/15/20 12:15 ORREC 0002 ans1 1520
123456 8/15/20 12:17 ORREC 0002 ans1 1522
我需要根据日期和时间获取每个form / formseq / anscode的最后一个条目
所以我得到的三个结果是
AcctNo EntryDate EntryTime Form FormSeq anscode answer
123456 8/14/20 07:05 ORREC 0001 ans1 1245
123456 8/14/20 07:05 ORREC 0001 ans2 testing
123456 8/15/20 12:17 ORREC 0002 ans1 1522
select AcctNo,EntryDate,EntryTime,Form,FormSeq,anscode,answer
from TableName
where
Group By AcctNo,Anscode
解决方法
下面是一个完整的示例。它与您的数据输出不完全匹配。但这确实与“根据日期和时间获取每个表单/ formseq / anscode的最后一个条目”相匹配。因此,它将返回每个日期的最后一个条目。如果您希望每个表单/ formseq / anscode的最后输入期是一个不同的查询。
CREATE TABLE public.test_table (
acctno integer,entrydate date,entrytime time without time zone,form character varying,formseq character varying,anscode character varying,answer character varying
);
COPY public.test_table (acctno,entrydate,entrytime,form,formseq,anscode,answer) FROM stdin;
123456 2020-08-14 07:05:00 ORREC 0001 ans1 1245
123456 2020-08-13 07:07:00 ORREC 0001 ans1 1235
123456 2020-08-14 07:04:00 ORREC 0001 ans2 test
123456 2020-08-14 07:05:00 ORREC 0001 ans2 testing
123456 2020-08-15 12:15:00 ORREC 0002 ans1 1520
123456 2020-08-15 12:17:00 ORREC 0002 ans1 1522
\.
SELECT
distinct on(entrydate,formSeq,anscode) acctno,answer
from
test_table
WHERE
acctNo = 123456
ORDER BY
entrydate,entrytime desc;
acctno | entrydate | entrytime | form | formseq | anscode | answer
--------+------------+-----------+-------+---------+---------+---------
123456 | 2020-08-13 | 07:07:00 | ORREC | 0001 | ans1 | 1235
123456 | 2020-08-14 | 07:05:00 | ORREC | 0001 | ans1 | 1245
123456 | 2020-08-14 | 07:05:00 | ORREC | 0001 | ans2 | testing
123456 | 2020-08-15 | 12:17:00 | ORREC | 0002 | ans1 | 1522
第二个查询,其输出类似于您的数据示例:
SELECT DISTINCT ON (form,anscode)
acctno,answer
FROM
test_table
ORDER BY
form,entrydate + entrytime DESC;
acctno | entrydate | entrytime | form | formseq | anscode | answer
--------+------------+-----------+-------+---------+---------+---------
123456 | 2020-08-14 | 07:05:00 | ORREC | 0001 | ans1 | 1245
123456 | 2020-08-14 | 07:05:00 | ORREC | 0001 | ans2 | testing
123456 | 2020-08-15 | 12:17:00 | ORREC | 0002 | ans1 | 1522
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。