PostgreSQL 在当前查询中按日期过滤

问题描述 投票:0回答:1

初始数据: 基地

有一个数据库查询:

SELECT accounts.number acc, counters.service serv, meter_pok.date, counters.tarif, meter_pok.value
    FROM stack.accounts
    LEFT JOIN stack.counters ON counters.acc_id = accounts.row_id
    LEFT JOIN stack.meter_pok ON meter_pok.acc_id = accounts.row_id AND meter_pok.counter_id = counters.row_id
    WHERE accounts.type = 3 AND counters.service = 100

执行时返回以下内容:

"acc","serv","date","tarif","value"
111,100,"2023-01-30",1,100
111,100,"2023-02-25",1,100
122,100,"2023-01-25",1,100
122,100,"2023-02-27",1,50
133,100,"2023-01-25",1,100
133,100,"2023-02-27",1,900
144,100,"2023-02-27",1,0
301,100,"2023-01-25",1,200
301,100,"2023-02-27",1,40
301,100,"2023-02-27",1,-90
501,100,"2023-01-25",1,100
501,100,"2023-02-27",1,50
402,100,NULL,1,NULL
401,100,NULL,1,NULL
502,100,NULL,1,NULL

如何添加按最新日期过滤?得到以下结果:

"acc","serv","date","tarif","value"
111,100,"2023-02-25",1,100
122,100,"2023-02-27",1,50
133,100,"2023-02-27",1,900
144,100,"2023-02-27",1,0
301,100,"2023-02-27",1,40
301,100,"2023-02-27",1,-90
501,100,"2023-02-27",1,50

试过这个查询,没有结果...

SELECT accounts.number acc, counters.service serv, meter_pok.date, counters.tarif, meter_pok.value
    FROM stack.accounts
    LEFT JOIN stack.counters ON counters.acc_id = accounts.row_id
    LEFT JOIN stack.meter_pok ON meter_pok.acc_id = accounts.row_id AND meter_pok.counter_id = counters.row_id
    WHERE accounts.type = 3 AND counters.service = 100 AND meter_pok.date = (SELECT MAX(meter_pok.date) FROM stack.meter_pok)
sql postgresql filter
1个回答
1
投票

您可以使用窗口函数来实现!这些方面的东西应该可以解决问题:

SELECT * FROM (
SELECT
  accounts.number acc,
  counters.service serv,
  meter_pok.date,
  counters.tarif,
  meter_pok.value,
  ROW_NUMBER () OVER (
    PARTITION BY accounts.number
    ORDER BY meter_pok.date DESC
  ) AS row_num
FROM stack.accounts
LEFT JOIN stack.counters ON counters.acc_id = accounts.row_id
LEFT JOIN stack.meter_pok ON meter_pok.acc_id = accounts.row_id AND meter_pok.counter_id = counters.row_id
WHERE accounts.type = 3
AND counters.service = 100
)
WHERE row_num = 1;
© www.soinside.com 2019 - 2024. All rights reserved.