I'm trying to create output that is along the lines of:
days_since, item_count
7, 0
30, 1
90, 2
and I want to provide the values for days_since
as a list, something like:
SELECT d.days, d.item_count
FROM (
VALUES (7, 0), (30, 1), (90, 2)
) d (days, item_count)
except for the item_count
I need to use days
as part of a query that counts results for some condition ( is_a_thing
), eg:
SELECT COUNT(CASE WHEN is_a_thing THEN 1 END) AS item_count
FROM items
WHERE created >= CURRENT_DATE - 30
but the date to compare against (30 here) should be days
from the list.
Unfortunately, I'm not sure how to join VALUES
to the SELECT
and be able to use the former in the latter.
MySQL does not support that syntax (ie you cannot create a derived table with VALUES()
.
Very recent versions have the VALUES(ROW ...)
syntax:
SELECT d.days, d.item_count
FROM (VALUES ROW(7, 0), ROW(30, 1), ROW(90, 2)) d (days, item_count)
In earlier versions, we have to restort UNION ALL
:
SELECT d.days, d.item_count
FROM (
SELECT 7 days, 0 item_count
UNION ALL SELECT 30, 1
UNION ALL SELECT 90, 2
) d
I suspect that the query you want is:
SELECT d.days, SUM(CASE WHEN is_a_thing THEN 1 ELSE 0 END)item_count
FROM (VALUES ROW(7), ROW(30), ROW(90)) d (days)
LEFT JOIN items i
ON i.created >= CURRENT_DATE - INTERVAL d.days
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.