Im practicing with the OE schema database on SQL Developer, and I cant figure out how to fix this issue. Im trying to get the total spent by customers summarized by the state and the year/month.
My sql code:
SELECT
c.cust_address.state_province,
SUM(o.order_total) AS Total_of_Sales,
TO_CHAR(o.order_date, 'YYYY-MM') AS Year_Month
FROM
oe.customers c,
oe.orders o
WHERE
c.customer_id = o.customer_id
GROUP BY
c.cust_address.state_province,
o.order_date
ORDER BY
o.order_date;
Result of query:
[ ]
However, as you can see here, the data of the state and YEAR/MONTH are still not grouped up. Instead, they have 3 rows for each state in the same month year when I need them to be summed it one.
May anyone guide me on how to correct my code to get my desired results?
First, never use commas in the FROM
clause. Always use proper, explicit JOIN
syntax. This is even more important if you are learning SQL. Don't learn bad habits!
You need to aggregate by the Year_Month
expression:
SELECT c.cust_address.state_province,
SUM(o.order_total) AS Total_of_Sales,
TO_CHAR(o.order_date, 'YYYY-MM') AS Year_Month
FROM oe.customers c JOIN
oe.orders o
ON c.customer_id = o.customer_id
GROUP BY c.cust_address.state_province, TO_CHAR(o.order_date, 'YYYY-MM')
ORDER BY TO_CHAR(o.order_date, 'YYYY-MM');
In some databases, you could use the column alias ( Year_Month
) in the GROUP BY
. Oracle is not one of those databases.
You should use Year_Month ... TO_CHAR(o.order_date, 'YYYY-MM') in group by .. (and order by)
SELECT c.cust_address.state_province,
SUM(o.order_total) AS Total_of_Sales,
TO_CHAR(o.order_date, 'YYYY-MM') AS Year_Month
FROM oe.customers c,
oe.orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.cust_address.state_province, TO_CHAR(o.order_date, 'YYYY-MM')
ORDER BY TO_CHAR(o.order_date, 'YYYY-MM');
otherwise you obtain the same granularity of the o.order_date
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.