月计算程序

时间:2014-01-06 12:08:11

标签: sql sql-server

名为Data的表

coloumns是Id,Name,Supply,Demand,Date,Value

创建一个

的过程

q1将包含Quarter-1的供应指数(JAN-MAR,供应总和/需求总和),

q2将包含第二季度的供应指数(APR-JUN,供应总和/需求总和),

q3将包含第3季度的供应指数(JUL-SEP,供应总和/需求总和),

Q4将包含供应指数q4(OCT-DEC,供应总和/需求总和),YR将包含给定年份的供应指数(JAN-DEC,供应总和) /需求总和),它由值

分隔

示例输入:

ID      Name     Suppply    Demand     date          value
1        A         10        5         01 04 2001    20
2        B          4        1         01 04 2001    20
3        A          4        2         02 01 2005    10
4        A          4        2         02 02 2005    10
5        B          4        1         01 07 2001    20

预期产出

Name   value    q1    q2     q3    q4
A         10    4     0      0     0
A         20    0     2      0     0
B         20    0     4      4     0

1 个答案:

答案 0 :(得分:0)

所以你想要这样的东西:

CREATE TABLE #test 
  ( 
     id     INT, 
     name   CHAR(1), 
     supply INT, 
     demand INT, 
     dates  DATE, 
     value  INT 
  ) 

INSERT INTO #test 
VALUES     (1, 
            'A', 
            10, 
            5, 
            '20010401', 
            20) 

INSERT INTO #test 
VALUES     (2, 
            'B', 
            4, 
            1, 
            '20010401', 
            20) 

INSERT INTO #test 
VALUES     (3, 
            'A', 
            4, 
            2, 
            '20050102', 
            10) 

INSERT INTO #test 
VALUES     (4, 
           'A', 
            4, 
            2, 
           '20050202', 
            10) 

INSERT INTO #test 
VALUES     (5, 
            'B', 
            4, 
            1, 
            '20010107', 
            20) 

SELECT name, 
       value, 
       Isnull([q1], 0), 
       Isnull([q2], 0), 
       Isnull([q3], 0), 
       Isnull([q4], 0) 
FROM   (SELECT 'q' + Rtrim(Datepart(q, dates)) AS quarters, 
               name, 
               Sum(supply) / Sum(demand)       AS val, 
               value 
        FROM   #test 
        GROUP  BY Datepart(q, dates), 
                  name, 
                  value) p 
       PIVOT ( Sum(val) 
             FOR quarters IN ([Q1], 
                              [Q2], 
                              [Q3], 
                              [Q4])) AS pivottable; 

drop table #test

下次请尝试整理更多文字:)