在PostgreSQL中按月份中最近的日期筛选
我有这些桌子:在PostgreSQL中按月份中最近的日期筛选,sql,postgresql,Sql,Postgresql,我有这些桌子: CREATE TABLE table_a ( the_debt_pay_id varchar(8) NOT NULL, the_debtor_id varchar(8) NOT NULL, the_debt_paid timestamp NOT NULL ); INSERT INTO table_a VALUES ('LMUS0100', '32457601', '2020-03-01 06:59:32'), ('LMUS0202', '
CREATE TABLE table_a
(
the_debt_pay_id varchar(8) NOT NULL,
the_debtor_id varchar(8) NOT NULL,
the_debt_paid timestamp NOT NULL
);
INSERT INTO table_a
VALUES ('LMUS0100', '32457601', '2020-03-01 06:59:32'),
('LMUS0202', '02377862', '2020-03-02 07:30:59'),
('LMUS0301', '40367879', '2020-03-02 09:34:20');
CREATE TABLE table_b
(
the_debtor_id varchar(8) NOT NULL,
the_invoice_id varchar(8) NOT NULL,
the_invoice_created date NOT NULL
);
INSERT INTO table_b
VALUES ('02377862', 'BE000017', '2020-02-04'),
('32457601', 'BE000018', '2020-03-01'),
('02377862', 'BE000019', '2020-03-03'),
('40367879', 'BE000020', '2020-03-17'),
('40367879', 'BE000021', '2020-03-19'),
('32457601', 'BE000022', '2020-04-01');
我想要的是,给定债务人id
,获得债务支付id
和发票id
,根据债务人支付的和创建的的当月最近日期,计算当月发生的一次或多次事件。这应该是预期的表格:
the_debt_pay_id the_invoice_id hits
LMUS0100 BE000018 1
LMUS0202 BE000019 1
LMUS0301 BE000020 2
我有点卡住了,因为表b没有被债务支付id索引。如果您有任何帮助,我们将不胜感激。回答关于表b未被债务支付id索引的部分
这里的常量似乎是债务人id
您可以在select语句中将表拉到一起,并为每个表分配一个别名(在本例中为f+g)
然后你可以这样加入他们
SELECT
f.the_debtor_id,
f.the_debt_pay_id,
g.the_invoice_id
FROM table_a f
JOIN table_b g
ON g.the_debtor_id = f.the_debtor_id
虽然索引联接列通常是一个好主意,但没有任何东西需要它。只要可以为它创建有效的布尔表达式,就可以加入任何内容。这里的连接只是来自每个表的\u id匹配。Ticker是用于确定“最近日期”和当月发票数量(点击数)的日期操纵。看小提琴
这有什么意义吗?通常,发票是在付款之前发送的,人们并不总是立即付款。Hello@LaurenzAlbe,事实上,在某些国家,人们付款,发票可以延迟,并在付款后发送。Hello Dallas,你错过了一点,即选择月份。无论如何,谢谢你的时间。
select distinct on(the_debt_pay_id)
the_debt_pay_id,the_invoice_id, hits
from (
select a.the_debt_pay_id
, b.the_invoice_id
, count(*) over(partition by a.the_debtor_id, extract('month' from b.the_invoice_created)
order by a.the_debtor_id ) hits
from table_a a
join table_b b
on b.the_debtor_id = a.the_debtor_id
order by a.the_debt_pay_id
, greatest(a.the_debt_paid,b.the_invoice_created::timestamp)-
least(a.the_debt_paid,b.the_invoice_created::timestamp)
) s;