SQL Server选择Montly租车计算器

时间:2016-04-15 09:56:48

标签: sql sql-server

我有一个RentTable

Mark      MonthlyRental   dailyRental   InDate        OutDate
-------------------------------------------------------------------
Mercedes    5000             166,67     01.01.2016    NULL
Renault     3000             100,00     01.01.2016    20.03.2016
Ford        4000             133,33     01.02.2016    NULL

我想做一个如下报告:

Mark    MonthlyRental   DailyRental    InDate       OutDate    January  February    March   April
---------------------------------------------------------------------------------------------------------
Mercedes    5000          166,67       01.01.2016   NULL        5000    5000    5000    5000
Renault     3000          100          01.01.2016   20.03.2016  3000    3000    2000    0
Ford        4000          133,33       01.02.2016   10.06.2016  4000    4000    4000    4000

1 个答案:

答案 0 :(得分:2)

可能是这样的东西

-- first into into a #temp table the list of dates that you want to turn to columns
;with cte (datelist, maxdate) as
(
    select min(InDate) datelist, max(OutDate) maxdate
    from RentTable
    union all
    select dateadd(mm, 1, datelist), maxdate
    from cte
    where datelist < maxdate
) 
select c.datelist
into #tempDates
from cte c

select *
from
(
    select b.Mark,b.MonthlyRental,b.DailyRental,b.InDate,b.OutDate,
        datename(month, datelist) PivotDate
    from #tempDates d
    left join RentTable b
        on d.datelist between b.InDate and ISNULL(b.OutDate,GETDATE())
) x
pivot
(
    SUM(MonthlyRental)
    for PivotDate in ([January],[February],[March],[April])
) p;