SQL查询包括月份列?

时间:2012-11-05 22:36:17

标签: sql sql-server tsql

我想知道我是否可以在输出列数月的SQL查询上获得一些想法或方向。这是我当前的查询..

select A.assetid, A.Acquisition_Cost, B.modepreciaterate from FA00100 A
inner join FA00200 B on A.assetindex = B.assetindex
where MoDepreciateRate != '0'

我想添加更多看起来如此的列:

select assetid, acquisition_cost, perdeprrate, Dec_2012, Jan_2013, Feb_2013....

where Dec_2012 = (acquisition_cost - MoDepreciateRate*(# of months))
and Jan_2013 = (acquisition_cost - MoDepreciateRate*(# of months))

其中月数可以改变。

任何帮助都会非常感激。谢谢!

以下是我希望输出与'#of months'= 4

的示例
assetid SHRTNAME    Acquisition_Cost    perdeprrate Dec_2012    Jan_2013    Feb_2013    Mar_2013
CS-013  GEH INTEG   17490.14            485.83      17004.31    16518.48    16032.65    15546.82
CS-014  WEB BRD     14560               404.4507    14155.5493  13751.0986  13346.6479  12942.1972

1 个答案:

答案 0 :(得分:0)

试试这个:

--setup
create table #fa00100 (assetId int, assetindex int, acquisitionCost int, dateAcquired date)
create table #fa00200 (assetIndex int, moDepreciateRate int, fullyDeprFlag nchar(1), fullyDeprFlagBit bit)

insert #fa00100 
      select 1, 1, 100, '2012-01-09'
union select 2, 2, 500, '2012-05-09'
insert #fa00200
      select 1, 10, 'N', 0
union select 2, 15, 'Y', 1

--solution
create table #dates (d date not null primary key clustered)
declare @sql nvarchar(max)
, @pivotCols nvarchar(max)
, @thisMonth date
, @noMonths int = 4

set @thisMonth = cast(1 + GETUTCDATE() - DAY(getutcdate()) as date)
select @thisMonth
while @noMonths > 0
begin
    insert #dates select DATEADD(month,@noMonths,@thisMonth) 
    set @noMonths = @noMonths - 1
end

select @sql = ISNULL(@sql + NCHAR(10) + ',', '') 
--+ ' A.acquisitionCost - (B.moDepreciateRate * DATEDIFF(month,dateAcquired,''' + convert(nvarchar(8), d, 112) + ''')) ' --Original Line
    + ' case when A.acquisitionCost - (B.moDepreciateRate * DATEDIFF(month,dateAcquired,''' + convert(nvarchar(8), d, 112) + ''')) <= 0 then 0 else A.acquisitionCost - (B.moDepreciateRate * DATEDIFF(month,dateAcquired,''' + convert(nvarchar(8), d, 112) + ''')) end ' --new version

+ quotename(DATENAME(month, d) + '_' + right(cast(10000 + YEAR(d) as nvarchar(5)),4))
from #dates

set @sql = 'select A.assetid
, A.acquisitionCost
, B.moDepreciateRate 
,' + @sql + '
from #fa00100 A
inner join #fa00200 B 
    on A.assetindex = B.assetindex
where B.fullyDeprFlag = ''N''
and B.fullyDeprFlagBit = 0
'
--nb: B.fullyDeprFlag = ''N'' has double quotes to avoid the quotes from terminating the string
--I've also included fullyDeprFlagBit to show how the SQL would look if you had a bit column - that will perform much better and will save space over using a character column

print @sql
exec(@sql)

drop table #dates 

    --remove temp tables from setup
drop table #fa00100
drop table #fa00200