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 表达式的聚合函数将数据从行转换为列:

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 回答