如何统计销售,城市,客户的货物使用oracle

时间:2017-12-02 09:26:53

标签: sql oracle

我有一个oracle视图,并包含商品详情的销售。它是这样的:

OrderId OrderDetailId GoodsId GoodsName UnitName SalesQty价格CustomerName国家城市

200138   ddd0a3b42adb   770   A   bag      5    18.00   AAAA    USA     NewYork  
223448   70ca7ceb41c7   193   D   bottle   10   10.00   BBB     USA     NewYork  
200118   ab472857573e   1286  F   cup      8    50.00   CCC     China   Beijing    
244028   230a43920667   770   A   bag      20   18.00   CCC     China   Beijing    
251118   118fc2b3839b   5929  C   box      40   6.00    DDDD    Japan   Tokyo    
200000   abd0a3b42ddd   770   A   bag      15   18.00   AAAA    USA     NewYork  
111118   11111113839b   5929  C   box      40   6.00    FFFF    Japan   Tokyo   

我想要一个SQL语句统计销售额,城市数量,每个商品的客户数量。结果应该是这样的:

GoodsId GoodsName SalesQty(UnitName)CityQty CustomerQty

GoodsId   GoodsName   SalesQty(UnitName)   CityQty  CustomerQty
770       A           40(bag)              2        2
193       D           10(bottle)           1        1
1286      F           8(cup)               1        1
5929      C           80(box)              1        2

如何编写sql统计语句?谢谢!

2 个答案:

答案 0 :(得分:1)

只需使用GROUP BY

即可
select GoodsId, GoodsName, UnitName, 
       sum(SalesQty) SalesQty, 
       count(distinct City) CityQty,
       count(distinct CustomerName) CustomerQty
from goods_view
group by GoodsId, GoodsName, UnitName

demo

答案 1 :(得分:0)

您可以使用cube,也包括数量的子&总数:

select GoodsId, GoodsName||'('||UnitName||')' GoodsName,
   sum(SalesQty) SalesQty, count(distinct City) CityQty, count(distinct CustomerName) CustomerQty
  from v_goods
 group by cube(GoodsId, GoodsName||'('||UnitName||')')
 order by GoodsId,GoodsName||'('||UnitName||')';