在 SQL 查询中使用 SUM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9574721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using SUM in an SQL query
提问by Monty
I'm trying to do a query where it adds up the totals for the orders from each customer.
我正在尝试做一个查询,它将每个客户的订单总数相加。
I have tried a few different ways but I am not sure the right way to do it.
我尝试了几种不同的方法,但我不确定正确的方法。
I've tried...
我试过了...
SELECT *
FROM Orders
SUM(Total) as Totals
COUNT(OrderID) as OrderAmt
GROUP BY CustomerID, OrderAmt, ShipName, Totals
I want to get this result....
我想得到这个结果......
=====================================
|CustomerID|Orders |ShipName|Total |
|==========|=======|========|=======|
|3334 |3 |Joe Blow|1100.00|
|----------|-------|--------|-------|
|114 |2 |Steve |280.00 |
|----------|-------|--------|-------|
|1221 |1 |Sue |250.00 |
|----------|-------|--------|-------|
|3444 |1 |Bob |22.00 |
=====================================
From this table...
从这张表...
|===================================|
|CustomerID|OrderID|ShipName|Total |
|==========|=======|========|=======|
|3334 |232 |Joe Blow|400.00 |
|----------|-------|--------|-------|
|3334 |234 |Joe Blow|500.00 |
|----------|-------|--------|-------|
|3334 |231 |Joe Blow|200.00 |
|----------|-------|--------|-------|
|114 |235 |Steve |250.00 |
|----------|-------|--------|-------|
|114 |239 |Steve |30.00 |
|----------|-------|--------|-------|
|1221 |244 |Sue |250.00 |
|----------|-------|--------|-------|
|3444 |632 |Bob |22.00 |
|===================================|
What would be the correct SQL statement for this.
什么是正确的 SQL 语句。
回答by Sean Carpenter
Sum
and count
can be used to get the result you want:
Sum
并且count
可以用来得到你想要的结果:
select CustomerID, count(*) as Orders, ShipName, sum(Total) as Total
from Table
group by CustomerID, ShipName
order by count(*) desc;
回答by Thit Lwin Oo
select CustomerID, count(OrderID) Orders, ShipName, sum(Total) Total
from Order_TAB
group by CustomerID, ShipName