SQL 06 Window and Date Time Functions 3
SQL 06 Window and Date Time Functions 3
SELECT market_start_datetime,
DATE_ADD(market_start_datetime, INTERVAL 30 MINUTE) AS mktstrt_date_
plus_30min
FROM farmers_market.datetime_demo
SELECT
x.customer_id,
x.market_date,
LAG(x.market_date, 1) OVER(PARTITION BY
x.customer_id ORDER BY x.market_date) AS last_prchs,
DATEDIFF(x.market_date, LAG(x.market_date, 1)
OVER(PARTITION BY x.customer_id ORDER BY
x.market_date)) AS days_bw_prch
FROM (
SELECT DISTINCT customer_id,
market_date
FROM customer_purchases
) AS x
Question: today’s date is May 31, 2019, and the marketing director of the farmer’s market wants to give
infrequent customers an incentive to return to the market in June.
SELECT
customer_id,
COUNT(DISTINCT market_date) AS
market_count
FROM customer_purchases
WHERE DATEDIFF('2019-05-31',
market_date) BETWEEN 0 AND 31
GROUP BY customer_id
HAVING market_count = 1
Question: Today’s date is May 31, 2019, and the marketing director of the farmer’s market wants to
give infrequent customers(with only 1 purchase) an incentive to return to the market in April.
SELECT x.customer_id,
COUNT(DISTINCT x.market_date) AS market_count
FROM (
SELECT DISTINCT customer_id, market_date
FROM farmers_market.customer_purchases
WHERE DATEDIFF(market_date, '2019-05-31') <= 31
)x
GROUP BY x.customer_id
HAVING COUNT(DISTINCT market_date) = 1
Reference DateTime Functions
- https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html