按年和按季度进行数据SQL

时间:2018-07-12 13:44:10

标签: c# sql asp.net database pivot

我需要一种查询SQL表并按季度和年份取回数据的方法。   听听我的数据格式[![在此处输入图片描述] [1]] [1]

enum CommonError: Error {
    case input
    case output
}

enum RareError: Error {
    case language
    case mathematics
}

let error: Error = RareError.language
// or
let error: Error = URLError(.cancelled)

switch error {
case CommonError.input:     print("Common input error")
case CommonError.output:    print("Common output error")
case RareError.language:    print("Rare language error") // This is executed
case RareError.mathematics: print("Rare mathematics error")

case URLError.cancelled: print("URLError -> cancelled") // - or this
case URLError.timedOut:  print("URLError -> timed out")

default: print("The error is unknown; maybe you should consider throwing it now?")
}

1 个答案:

答案 0 :(得分:1)

First i will create my table

create table radhasapna (id int identity(1,1), [Year] int, Q int, Q2 int, Q3 int, Q4 int)

insert into radhasapna ([Year] , Q , Q2 , Q3 , Q4 ) values
(2000,  200,    456,    45, 35  ),
(2000,  200,    435,    435,    545 ),
(2000,  200,    454,    43, 45  ),
(2000,  200,    45, 435,    4   ),
(2001,  300,    4,  43, 545 ),
(2001,  300,    43, 4,  56  ),
(2001,  300,    4,  4,  4   ),
(2001,  300,    43, 43, 6   ),
(2001,  300,    4,  56, 34  ),
(2002,  400,    4,  34, 43  ),
(2002,  400,    43, 45, 6   ),
(2002,  400,    4,  45, 4   ),
(2002,  400,    43, 34, 54  ),
(2002,  400,    45, 45, 6)

declare @years integer = (SELECT COUNT(DISTINCT [YEAR]) FROM radhasapna)
print @years
declare @minY nvarchar(10) = (SELECT CAST(MIN([YEAR]) as nvarchar) FROM radhasapna)

declare @sql nvarchar(max)
declare @i int = 1
set @sql = ';with cte as (
SELECT ROW_NUMBER() OVER (PARTITION BY [YEAR] ORDER BY id) as r,
         ID,        YEAR,   Q1, Q2, Q3, Q4, [From]  ,[To]
    FROM   radhaa )
SELECT '


WHILE @i <= @years
begin
    set @sql = @sql + stuff('aXX', 2,2, @i) + '.*'
    if @i < @years
    begin
        set @sql = @sql + ','
    end 
    set @i = @i + 1
end



set @sql = @sql + ' from cte a1 '

set @i = 2
WHILE @i <= @years
begin
    declare @s nvarchar(10) = stuff('aXX', 2,2, @i)
    declare @prevS nvarchar(10) = stuff('aXX',2,2,@i-1)
    set @sql = @sql + 'left outer join cte ' + @s + ' on ' + @s + '.[YEAR] = ' + @prevS + '.[YEAR] + 1 and a1.r = ' + @s + '.r '
    set @i = @i + 1
end
set @sql = @sql + 'where a1.[YEAR] = ' + @minY + ' order by a1.r'
EXEC sp_executesql @sql
print @sql