[英]Extracting entries from a specific month in SQL
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).我正在尝试从名为
orders
的表中计算 3 月份每个客户购买的总收入,其中order_date
的格式为datetime
时间(例如 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
? 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?您是否考虑将 WHERE 子句放在 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?
您是收到错误消息还是只是没有返回预期值/行数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.