避免使用求和的笛卡尔积

时间:2019-06-05 09:14:56

标签: sql postgresql-9.4 cartesian-product

我想总结stake表中的tickets,并按照customer_id表中的date_trunc('day')bonus表中的CREATE TABLE tickets ( ticket_id integer, customer_id integer, stake integer, reg_date date ); CREATE TABLE bonus ( bonus_id integer, customer_id integer, reg_date date ); insert into tickets values (1,100, 12,'2019-01-10 11:00'), (2,100, 10,'2019-01-10 12:00'), (3,100, 30,'2019-01-10 13:00'), (4,100, 10,'2019-01-11 14:00'), (5,100, 15,'2019-01-11 15:00'), (6,102, 25,'2019-01-10 10:00'), (7,102, 25,'2019-01-10 11:10'), (8,102, 13,'2019-01-11 12:40'), (9,102, 9,'2019-01-12 15:00'), (10,102, 7,'2019-01-13 18:00'), (13,103, 15,'2019-01-12 19:00'), (14,103, 11,'2019-01-12 22:00'), (15,103, 11,'2019-01-14 02:00'), (16,103, 11,'2019-01-14 10:00') ; insert into bonus values (200,100,'2019-01-10 05:00'), (201,100,'2019-01-10 06:00'), (202,100,'2019-01-10 15:00'), (203,100,'2019-01-10 15:50'), (204,100,'2019-01-10 16:10'), (205,100,'2019-01-10 16:15'), (206,100,'2019-01-10 16:22'), (207,100,'2019-01-11 10:10'), (208,100,'2019-01-11 16:10'), (209,102,'2019-01-10 10:00'), (210,102,'2019-01-10 11:00'), (211,102,'2019-01-10 12:00'), (212,102,'2019-01-10 13:00'), (213,103,'2019-01-11 11:00'), (214,103,'2019-01-11 18:00'), (215,103,'2019-01-12 15:00'), (216,103,'2019-01-12 16:00'), (217,103,'2019-01-14 02:00') select customer_id, date_trunc('day', b.reg_date), sum(t.stake) from tickets t join bonus b using (customer_id) where date_trunc('day', b.reg_date) = date_trunc('day', t.reg_date) group by 1,2 order by 1 进行分组。

问题在于行正被相乘,我不知道如何解决。

https://www.db-fiddle.com/f/yWCvFamMAY9uGtoZupiAQ/4

102,2019-01-10, 50

客户102的输出应为:

{{1}}

1 个答案:

答案 0 :(得分:1)

好的,我想您想获取const scrollHeightSpy = jest .spyOn(document.documentElement, 'scrollHeight', 'get') .mockImplementation(() => 100); 表中列stake的摘要数据,并且记录的tickets对已经出现在第二个表customer_id, reg_date中,并且所有业务与bonus无关,对吗? bonus_id中的customer_id, reg_date对是重复的,因此您需要在其上有一个bonus,然后从票证中distinct join数据。完整的SQL和结果如下:

sum