0

ここではSQL初心者です。Oracle DB のアイテムのテーブルを見て、アイテムを年ごとに (それぞれ別の列に) エクスポートし、それらをユーザー ID でグループ化し、合計フィールドを合計したいと考えていました。

次のような日付範囲で個別にエクスポートできます

WHERE DATE > '01-JAN-13'
AND DATE < '31-DEC-13'

私のテーブル「CUSTOMER_ORDERS」はこのように見えますこれが私のテーブルの外観です

Customer Name | Customer ID | Date | Sale
_________________________________________
Customer 1 | CUS01 | 05-JAN-13 | 110.00
Customer 2 | CUS02 | 06-JAN-11 | 110.00
Customer 3 | CUS03 | 07-JAN-12 | 70.00
Customer 1 | CUS01 | 05-JAN-12 | 10.00
Customer 2 | CUS02 | 05-JAN-11 | 210.00

理想的には、このようなものをエクスポートしたい

Customer Name | Customer ID | 2011 Total | 2012 Total | 2013 Total
_________________________________________
Customer 1 | CUS01 | 0   | 10  | 110
Customer 2 | CUS02 | 320 | 0   |  0
Customer 3 | CUS03 | 0   | 70  |  0

これは非常に単純だと思いますが、正しい方法がわかりません。

4

2 に答える 2

5

CASE 式で集計関数を使用して、データを行から列に PIVOT できます。

select 
  CustomerName,
  CustomerID, 
  sum(case when to_char(dt, 'YYYY') = 2011 then Sale else 0 end) Total_2011,
  sum(case when to_char(dt, 'YYYY') = 2012 then Sale else 0 end) Total_2012,
  sum(case when to_char(dt, 'YYYY') = 2013 then Sale else 0 end) Total_2013
from CUSTOMER_ORDERS
group by CustomerName, CustomerID;

SQL Fiddle with Demoを参照してください。

Oracle のバージョンによっては、Oracle 11g+ を使用している場合、PIVOT 関数を使用できる場合があります。

select *
from
(
  select CustomerName, CustomerId, 
    'Total_'||to_char(dt, 'YYYY') year, sale
  from CUSTOMER_ORDERS
) 
pivot
(
  sum(sale)
  for year in ('Total_2011', 'Total_2012', 'Total_2013')
);

デモで SQL Fiddle を参照してください

于 2013-07-30T21:51:10.930 に答える
0

自己結合の力を利用して、必要な方法でデータをサブセット化します。次のようなものを試してください

select c.ID , c.Name , sum(c2011.Sale) , sum(c2012.Sale) , sum( c2013.Sale )
from      ( select distinct c.ID , c.Name from customer_order ) c
left join customer_order c2011 on c2011.id = c.id and year(c.Date) = 2011
left join customer_order c2012 on c2012.id = c.id and year(c.Date) = 2012
left join customer_order c2013 on c2013.id = c.id and year(c.Date) = 2013
group by c.ID , c.Name
order by c.ID , c.Name

望ましい結果を得るために。あるいは...

select c.ID , c.Name ,
       sum(case when year(c.Date) = 2011 then c.Sale else 0 end) ,
       sum(case when year(c.Date) = 2012 then c.Sale else 0 end) ,
       sum(case when year(c.Date) = 2013 then c.Sale else 0 end)
from customer_order c
group by c.ID , c.Name
order by c.ID , c.Name
于 2013-07-30T21:50:48.983 に答える