简体   繁体   English

用多个分组制作一条sql语句

[英]Making a sql statement with multiple grouping

I'm trying to make a summary report based off my database. 我正在尝试根据数据库创建摘要报告。 It must be grouped by location by week by year and I want to total the amount of orders in that grouping. 它必须按位置逐周分组,我想对该分组中的订单总数进行总计。

It needs to look something like: 它需要看起来像:

Year    Week    Location    Total Amount
2014    1       Atlanta     22,000 
2014    1       Schaumberg  32,566 
2014    1       Dallas      32,567 
2014    1       New York    32,356 
2014    2       Atlanta     22,000 
2014    2       Schaumberg  32,566 
2014    2       Dallas      32,567 
2014    2       New York    32,356 

My table (system_order) structure is setup like this: 我的表(system_order)结构的设置如下:

Order   Amount  Location    Week    Year
1       1895    Schaumberg  1       2014
2       1295    Atlanta     1       2014
3       1895    Atlanta     1       2014
4       1895    New York    1       2014
5       1495    Dallas      2       2014
6       1695    Schaumberg  2       2014
7       1895    Schaumberg  2       2014
8       1895    Dallas      2       2014
9       1895    New York    2       2014

Can this be done in one sql statement? 可以在一个sql语句中完成吗?

SELECT Year, Week, Location, sum(Amount) as 'Total Amount'
FROM [system_order] 
GROUP BY Location, Week, Year

I have not testest. 我没有testest。 Bus this should work. 公共汽车这应该工作。

select sum(amount), year,week,location
from (system_order)
group by Location, week, year
order by sum(amount)

Usually you have to put the rows you selected into the group by clause. 通常,您必须将选择的行放入group by子句中。 The exception is if they are in an aggregate function in the select clause. 例外是它们是否在select子句的聚合函数中。

This right here should work. 这应该在这里起作用。

Select Year
       ,Week
       ,Location
       ,sum(amount) as 'Total_Amount'
from (system_order)
group by Year
       ,Week
       ,Location

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

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