Skip to content

Instantly share code, notes, and snippets.

@grihabor
Last active February 26, 2018 10:16
Show Gist options
  • Save grihabor/27c237cfc110448cfffa90eeedd63159 to your computer and use it in GitHub Desktop.
Save grihabor/27c237cfc110448cfffa90eeedd63159 to your computer and use it in GitHub Desktop.
Get products which are first products that people buy
select
ProductID,
sum(case
when first_order_datetime is null then 0
else 1
end)
from order_lines
left join (
select
min(Datetime) as first_order_datetime,
CustomerID as order_customer_id
from order_lines
group by CustomerID
) as first_orders
on Datetime = first_order_datetime
and CustomerID = order_customer_id
group by ProductID
create table order_lines(
OrderLineID integer,
ProductID integer,
Datetime datetime,
CustomerID integer
);
insert into order_lines () values (100, 200, '2017-11-20 00:00:00', 300);
insert into order_lines () values (100, 201, '2017-11-20 00:00:00', 300);
insert into order_lines () values (100, 202, '2017-11-20 00:00:00', 300);
insert into order_lines () values (100, 203, '2017-11-21 00:00:00', 300);
insert into order_lines () values (100, 204, '2017-11-21 00:00:00', 300);
insert into order_lines () values (100, 202, '2017-11-20 00:00:00', 301);
insert into order_lines () values (100, 203, '2017-11-20 00:00:00', 301);
insert into order_lines () values (100, 200, '2017-11-21 00:00:00', 301);
insert into order_lines () values (100, 201, '2017-11-21 00:00:00', 301);
insert into order_lines () values (100, 204, '2017-11-21 00:00:00', 301);
insert into order_lines () values (100, 200, '2017-11-21 00:00:00', 302);
insert into order_lines () values (100, 204, '2017-11-22 00:00:00', 302);
insert into order_lines () values (100, 205, '2017-11-22 00:00:00', 302);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment