在SQL

时间:2016-10-21 12:19:04

标签: sql

有人可以帮助我吗? 正如您从第一张图片(原始数据)中看到的那样,我的日期格式为" Mar-12"和2014,2015,2016和2017年的数据。 现在,我需要插入新专栏" year"我需要把这一年从1月14日,1月15日,1月16日,2月16日等等。 基本上,我认为我需要某种数据转置。 在第二张图片"最终订单"我以什么顺序显示我需要数据。

enter image description here

enter image description here

我不知道什么是dbms。 所以,这就是我的数据(原始)的样子:

Customer|Section|Data|Jan-14|Feb-14|Jan-15|Feb-15

Total    Fore     SR   10     20     30      35
Total    Fore     TK   5       4     12      10
===================================================

我需要以这种形式提供数据:

Customer|Section|Data| Year |Jan|Feb|

Total     Fore    SR  2014   10   20
Total     Fore    TK  2014   5    4
Total     Fore    SR  2015   30   35
Total     Fore    TK  2015   12   10

1 个答案:

答案 0 :(得分:0)

鉴于你的样本

create table t (Customer varchar(5),Section varchar(4), Data varchar(2), [Jan-14] int , [Feb-14] int, [Jan-15] int, [Feb-15] int)
insert into @t values
('Total' ,   'Fore' ,    'SR'  , 10 ,    20,     30,      35),
('Total' ,   'Fore' ,    'TK'  , 5  ,     4,     12,      10)

你可以解决这个问题,如果你的sql方言是ms sql server通过unpivoting然后按类似的方式分组

select    customer,section,data,yyyy,
            sum(case when mm='Jan' then dts else 0 end) as 'Jan',
            sum(case when mm='Feb' then dts else 0 end) as 'Feb'
 from
(
select      customer,section,data,
            dummy,
            substring(dummy,1,3) as mm,
            concat('20',substring(dummy,5,2)) as yyyy,
            dts
from
(
select  customer,section,data,
        [Jan-14] , [Feb-14] , [Jan-15] , [Feb-15]
from t
) pvt
UNPIVOT
   (dts FOR dummy IN 
      ([Jan-14] , [Feb-14] , [Jan-15] , [Feb-15])
)AS unpvt
) x
 group by customer,section,yyyy,data

结果

customer section data yyyy Jan         Feb
-------- ------- ---- ---- ----------- -----------
Total    Fore    SR   2014          10          20
Total    Fore    TK   2014           5           4
Total    Fore    SR   2015          30          35
Total    Fore    TK   2015          12          10

如果你的sql方言没有unpivot,你可以

select    customer,section,data,yyyy,
            sum(case when mm='Jan' then dts else 0 end) as 'Jan',
            sum(case when mm='Feb' then dts else 0 end) as 'Feb'
 from
( 
select   customer,section,data,2014 as yyyy,'Jan' as mm,[Jan-14] as dts from t
union all
select   customer,section,data,2014 as yyyy,'Feb' as mm,[Feb-14] as dts from t
union all
select   customer,section,data,2015 as yyyy,'Jan' as mm,[Jan-15] as dts from t
union all
select   customer,section,data,2015 as yyyy,'Feb' as mm,[Feb-15] as dts from t
)  x
 group by customer,section,yyyy,data

显然,如果你有一个未知/可变数量/很多列,这两种方法都很痛苦,在这种情况下你需要编写一个脚本来生成一个sql语句以提交给动态sql。