SQL语句将不同的日期范围分组为新列

时间:2013-07-30 21:43:28

标签: sql oracle

SQL初学者在这里。查看Oracle数据库中的项目表,并希望按年度导出项目(每个项目在一个单独的列中),按用户标识对它们进行分组,然后对总计字段求和。

我可以使用日期范围(例如

)单独导出它们
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

我确信这非常简单,我无法找到正确的方法。

2 个答案:

答案 0 :(得分: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 with Demo

答案 1 :(得分: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