I'm trying to calculate total revenues from each customer purchase in March from a table called orders
, where order_date
is in format of datetime
(eg 2019-03-04). However, I'm unsuccessful to obtain the results with either of the following options:
WITH cte_orders AS
(
SELECT
cust_id,
SUM(order_quantity * order_cost) AS revenue
FROM
orders
WHERE
DATEPART('month', order_date) = 3
GROUP BY
cust_id
)
SELECT cust_id, revenue
FROM cte_orders;
also
WHERE EXTRACT(month from order_date) = '03'
or
WHERE MONTH(order_date) = 03
doesn't work either. What's wrong with my syntax here?
Thanks everyone for the input, finally figured out the right way to do this:
WITH cte_orders AS
(
SELECT
cust_id,
SUM(order_quantity * order_cost) AS revenue,
FROM
orders
WHERE
EXTRACT('MONTH' FROM order_date :: TIMESTAMP) = 3
GROUP BY
cust_id
)
SELECT cust_id, revenue
FROM cte_orders;
with this it converted the date to timestamp and extracted March as required.
What about date_part
?
WITH cte_orders AS
(select cust_id
, SUM(order_quantity * order_cost) as revenue
from orders
WHERE date_part('month',TIMESTAMP order_date) = 3
group by cust_id)
select cust_id, revenue from cte_orders;
Did you consider putting the WHERE clause outside of the CTE?
WITH cte_orders AS
(
SELECT
cust_id,
SUM(order_quantity * order_cost) AS revenue
FROM
orders
WHERE
DATEPART('month', order_date) = 3
GROUP BY
cust_id
)
SELECT cust_id, revenue
FROM cte_orders
WHERE MONTH(order_date) = 03;
Also, it would be helpful if you let us know what (if any) results you are getting. Are you getting an error message or is it just not returning the expected values/row count?
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.