具有2列以上的SQL数据透视表

时间:2016-10-06 05:17:50

标签: sql

下面提到的是我的表。

ID  Comp        RYear   Elect   Compu   Maint
1   1st Comp    2012    30000   76000   0
3   1st Comp    2013    35000   0       0
4   2nd Comp    2012    50000   100000  18000

通过使用pivot我需要获得如下所述的结果。

    $scope.gridOptions.getRowStyle = function getRowStyleScheduled(params){      
       if(parseInt(params.node.id)%2==0) {
          return {'background-color': 'rgb(87, 90, 90)'}
       }else {
          return {'background-color': 'rgb(74, 72, 72)'}
       }
    };

有谁能建议我如何实现它?

2 个答案:

答案 0 :(得分:0)

请在此SQL Fiddle

中找到您的解决方案

以下是数据透视表的代码:

CREATE TABLE yt
    ([Id] int, [Comp] nvarchar(100), [RYear] int , [Category] nvarchar(100) , [Amount] int)
;

INSERT INTO yt
    ([Comp], [RYear], [Category] , [Amount])
VALUES
    ('1st Comp', '2012', 'Elect',30000),
    ('1st Comp', '2012', 'Compu',76000),
    ('1st Comp', '2013', 'Elect',35000),
    ('2nd Comp', '2012', 'Elect',50000),
    ('2nd Comp', '2012', 'Compu',100000),
    ('2nd Comp', '2012', 'Elect',18000)
;

枢轴程序

select *
from 
(
  select Comp, RYear, Category , Amount
  from yt
) src
pivot
(
  sum(Amount)
  for Category in ([Elect], [Compu])
) piv;

答案 1 :(得分:0)

(感谢@chirag_patel准备了一个测试用例)

MySQL没有特定的"支点功能"。 您可以在下面找到(sqlfiddle here)如何解决这种缺席问题(或多或少是跨数据库)

CREATE TABLE yt
    (Id int, Comp nvarchar(100), RYear int , Category nvarchar(100) , Amount int)
;

INSERT INTO yt
    (Id, Comp, RYear, Category , Amount)
VALUES
    (1,'1st Comp', '2012', 'Elect',30000),
    (2,'1st Comp', '2012', 'Compu',76000),
    (3,'1st Comp', '2013', 'Elect',35000),
    (4,'2nd Comp', '2012', 'Elect',50000),
    (5,'2nd Comp', '2012', 'Compu',100000),
    (6,'2nd Comp', '2012', 'Maint',18000)
;

select 
 Comp,
 RYear,
 min(ID) as ID,
 sum(case when Category='Elect' then Amount else 0 end) Elect,
 sum(case when Category='Compu' then Amount else 0 end) Compu,
 sum(case when Category='Maint' then Amount else 0 end) Maint
  from yt
 where Category in ('Elect','Compu','Maint') 
 group by 1,2;