我有订单和行表。
订单可以有一行或多行 一行引用产品(已购买的产品),date_at(您可以想到一张票。您可以使用此票的日期)
create table o (
id integer NOT NULL
);
CREATE TABLE line (
id integer NOT NULL,
order_id integer NOT NULL,
product_id integer NOT NULL,
date_at date,
time_at time,
);
我正在寻找每个日期有多少bookings/reservations
。
我可以获得每个日期(date_at, count)
的列表
select date(t3.date_at), count(*)
from (
select t1.id, date(t2.date_at) as date_at, count(*)
from o t1
inner join line t2 on t1.id = t2.order_id
group by t1.id, date(t2.date_at)) t3
group by date(t3.date_at);
现在我想要每个产品的结果。
即。我想要每个product_id,我想获得包含产品的订单的(date, count)
列表(至少有一行包含product_id
的订单)。
我可以在具有不同{product_id}
的循环中运行以下查询,但我想可能有更好的方法
select date(t3.date_at), count(*)
from (
select t1.id, date(t2.date_at) as date_at, count(*)
from o t1
inner join line t2 on t1.id = t2.order_id
where t2.product_id={product_id}
group by t1.id, date(t2.date_at)) t3
group by date(t3.date_at);
我正在使用postgres。
测试数据
insert into o(id)
values
(1);
insert into o(id)
values
(2);
insert into o(id)
values
(3);
insert into line (id, order_id, product_id, date_at)
values
(1, 1, 1, '2017-1-1');
insert into line (id, order_id, product_id, date_at)
values
(2, 1, 1, '2017-1-1');
insert into line (id, order_id, product_id, date_at)
values
(7, 1, 1, '2017-1-1');
insert into line (id, order_id, product_id, date_at)
values
(8, 2, 1, '2017-1-1');
insert into line (id, order_id, product_id, date_at)
values
(5, 2, 2, '2017-1-1');
insert into line (id, order_id, product_id, date_at)
values
(6, 1, 2, '2017-1-1');
insert into line (id, order_id, product_id, date_at)
values
(4, 1, 1, '2017-1-3');
insert into line (id, order_id, product_id, date_at)
values
(3, 3, 2, '2017-1-2');
我想我只需要再次分组......
select date(t3.date_at), t3.product_id, count(*)
from (
select t1.id, t2.date_at as date_at, t2.product_id as product_id, count(*) as c
from o t1
inner join line t2 on t1.id = t2.order_id
group by t1.id, t2.product_id, date(t2.date_at)) t3
group by t3.product_id, t3.date_at;
答案 0 :(得分:0)
如果您需要:对于每个产品,对于每个日期,包含至少一个该产品实例的唯一/不同订单数量的计数,则以下内容应足够。
select product_id, date_at, count(distinct order_id)
from line
group by product_id, date_at
order by product_id, date_at;