我正在尝试执行一个查询,该查询将每个客户的订单总数相加。
我尝试了几种不同的方法,但是我不确定这样做的正确方法。
我试过了…
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语句呢?
Sum并count可以用来获取所需的结果:
Sum
count
select CustomerID, count(*) as Orders, ShipName, sum(Total) as Total from Table group by CustomerID, ShipName order by count(*) desc;