简体   繁体   English

如何使用查询在Oracle SQL Developer中汇总数据?

[英]How to summarize data in Oracle SQL Developer with a query?

Im practicing with the OE schema database on SQL Developer, and I cant figure out how to fix this issue. 我在SQL Developer上使用OE模式数据库练习,我无法弄清楚如何解决这个问题。 Im trying to get the total spent by customers summarized by the state and the year/month. 我试图获得由州和年/月汇总的客户总支出。

My sql code: 我的sql代码:

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. 相反,它们在同一个月的每个州都有3行,我需要将它们相加一个。

May anyone guide me on how to correct my code to get my desired results? 任何人都可以指导我如何纠正我的代码以获得我想要的结果?

First, never use commas in the FROM clause. 首先, 永远不要FROM子句中使用逗号。 Always use proper, explicit JOIN syntax. 始终使用正确,明确的JOIN语法。 This is even more important if you are learning SQL. 如果您正在学习SQL,这一点就更为重要。 Don't learn bad habits! 不要学习坏习惯!

You need to aggregate by the Year_Month expression: 您需要通过Year_Month表达式进行聚合:

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 . 在某些数据库中,您可以使用GROUP BY的列别名( Year_Month )。 Oracle is not one of those databases. Oracle不是这些数据库之一。

You should use Year_Month ... TO_CHAR(o.order_date, 'YYYY-MM') in group by .. (and order by) 您应该在分组中使用Year_Month ... TO_CHAR(o.order_date,'YYYY-MM')..(和排序方式)

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 否则你获得o.order_date的相同粒度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM