在SQL查询中使用SUM

Mon*_*nty -3 sql

我正在尝试进行查询,其中汇总了每个客户的订单总数.

我尝试了几种不同的方法,但我不确定正确的方法.

我试过了...

SELECT *
FROM Orders
SUM(Total) as Totals
COUNT(OrderID) as OrderAmt
GROUP BY CustomerID, OrderAmt, ShipName, Totals
Run Code Online (Sandbox Code Playgroud)

我想得到这个结果....

=====================================
|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  |
=====================================
Run Code Online (Sandbox Code Playgroud)

从这张桌子......

|===================================|
|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  |
|===================================|
Run Code Online (Sandbox Code Playgroud)

什么是正确的SQL语句.

Sea*_*ter 24

Sum并且count可以用来获得你想要的结果:

select CustomerID, count(*) as Orders, ShipName, sum(Total) as Total
from Table
group by CustomerID, ShipName
order by count(*) desc;
Run Code Online (Sandbox Code Playgroud)

  • 当OP看起来没有尝试任何东西时,甚至花时间回答+1 (4认同)