Skip to content

Instantly share code, notes, and snippets.

@Farhaduneci
Created September 1, 2022 06:20
Show Gist options
  • Save Farhaduneci/d97a265a96ed643e078d6df545938f71 to your computer and use it in GitHub Desktop.
Save Farhaduneci/d97a265a96ed643e078d6df545938f71 to your computer and use it in GitHub Desktop.
8 Week SQL Challenge, Case Study #1, Danny's Diner
-- Case Study #1 - Danny's Diner
-- https://8weeksqlchallenge.com/case-study-1/
-- Solved on SQLite 3.39 by Farhad Uneci, August 2022
-- 1. What is the total amount each customer spent at the restaurant?
SELECT
customer_id AS 'Customer',
SUM(price) AS 'Paid'
FROM
sales
JOIN menu ON sales.product_id = menu.product_id
GROUP BY
customer_id
ORDER BY
'Paid' DESC,
'Customer';
-- 2. How many days has each customer visited the restaurant?
SELECT
customer_id,
COUNT(DISTINCT(order_date)) AS 'Visit Count'
FROM
sales
GROUP BY
customer_id;
-- 3. What was the first item from the menu purchased by each customer?
WITH Ranked AS (
SELECT
sales.customer_id AS 'Customer',
menu.product_name AS 'Product',
sales.order_date AS 'Date',
DENSE_RANK() OVER (
PARTITION BY sales.customer_id
ORDER BY
sales.order_date
) AS 'Rank'
FROM
sales
JOIN menu ON sales.product_id = menu.product_id
)
SELECT
DISTINCT Customer,
Product,
Date
FROM
Ranked
WHERE
Rank = 1;
-- 4. What is the most purchased item on the menu and how many times was it purchased by all customers?
SELECT
menu.product_name AS 'Product',
SUM(1) || ' ' || 'times' AS 'Sold'
FROM
sales
JOIN menu ON sales.product_id = menu.product_id
GROUP BY
sales.product_id
ORDER BY
'Sold' DESC
LIMIT
5;
CREATE TABLE sales (
"customer_id" VARCHAR(1),
"order_date" DATE,
"product_id" INTEGER
);
INSERT INTO sales
("customer_id", "order_date", "product_id")
VALUES
('A', '2021-01-01', '1'),
('A', '2021-01-01', '2'),
('A', '2021-01-07', '2'),
('A', '2021-01-10', '3'),
('A', '2021-01-11', '3'),
('A', '2021-01-11', '3'),
('B', '2021-01-01', '2'),
('B', '2021-01-02', '2'),
('B', '2021-01-04', '1'),
('B', '2021-01-11', '1'),
('B', '2021-01-16', '3'),
('B', '2021-02-01', '3'),
('C', '2021-01-01', '3'),
('C', '2021-01-01', '3'),
('C', '2021-01-07', '3');
CREATE TABLE menu (
"product_id" INTEGER,
"product_name" VARCHAR(5),
"price" INTEGER
);
INSERT INTO menu
("product_id", "product_name", "price")
VALUES
('1', 'sushi', '10'),
('2', 'curry', '15'),
('3', 'ramen', '12');
CREATE TABLE members (
"customer_id" VARCHAR(1),
"join_date" DATE
);
INSERT INTO members
("customer_id", "join_date")
VALUES
('A', '2021-01-07'),
('B', '2021-01-09');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment