在SQL查询中使用SUM

时间:2012-03-05 22:02:23

标签: sql

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

我尝试过几种不同的方法,但我不确定是否采取正确的方法。

我试过......

SELECT *
FROM Orders
SUM(Total) as Totals
COUNT(OrderID) as OrderAmt
GROUP BY CustomerID, OrderAmt, ShipName, Totals

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

=====================================
|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  |
=====================================

从这张表中......

|===================================|
|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  |
|===================================|

对此,正确的SQL语句是什么。

2 个答案:

答案 0 :(得分:24)

Sumcount可用于获得您想要的结果:

select CustomerID, count(*) as Orders, ShipName, sum(Total) as Total
from Table
group by CustomerID, ShipName
order by count(*) desc;

答案 1 :(得分:2)

select CustomerID, count(OrderID) Orders, ShipName, sum(Total) Total
from Order_TAB
group by CustomerID, ShipName