1

我想旋转一个选择语句。给出了“国家”、“商店”和“销售”列。

现在我想要一个像这样的输出:

         Store1  Store2 Store3
Country1   2342    2342   5675
Country2   5753    3274   7326
Country3   1543    4367   3367

所以基本上我需要每个商店、每个国家/地区的销售额。

输入来自(示例):

Country:    StoreNr:    ProductSold:
 Belgium         23             Car
 Belgium         23           House
Netherland       23             Car

输出将是:

             Store23
Belgium            2
Netherlands        1
4

1 回答 1

2

如果商店的数量是有限的,您可以使用以下方法之一:

  1. 使用count()聚合函数结合case表达式:

    -- sample of data. just for the sake of demonstration
    SQL> with t1(Country, StoreNr, ProductSold) as(
      2    select 'Belgium'   , 23,  'Car'   from dual union all
      3    select 'Belgium'   , 23,  'House' from dual union all
      4    select 'Netherland', 23,  'Car'   from dual union all
      5    select 'Belgium'   , 25,  'House' from dual
      6  )
      7  select country
      8       , count(case
      9                 when StoreNr = 23
     10                 then 1
     11               end) as storeNr_23
     12        , count(case
     13                 when StoreNr = 25
     14                 then 1
     15               end) as storeNr_25
     16    from t1
     17   group by country
     18  ;
    

    结果:

     COUNTRY    STORENR_23 STORENR_25
     ---------- ---------- ----------
     Belgium             2          1
     Netherland          1          0
    
  2. 从 Oracle 11g 及更高版本开始,pivot操作符如下:

    select *
      from (Select country as country
                 , country as country_cnt
                 , StoreNr
             from t1)
     pivot(                                 -- list all store numbers here
         count(country_cnt) for storenr in (  23 as StoreNr_23
                                            , 25 as StoreNr_25) 
     )                                       
    

    结果:

     COUNTRY    STORENR_23 STORENR_25
     ---------- ---------- ----------
     Belgium             2          1
     Netherland          1          0
    
于 2013-09-18T07:49:09.950 回答