完整的查詢:
declare @iter int
declare @max int
declare @test Table ([Id-rent_date] datetime, Car_return_date datetime, IdCar int)
set @iter = 0
select @max = max(year(Car_return_date) - year([Id-rent_date])) FROM Renting
WHILE(@iter < @max)
BEGIN
insert into @test
SELECT
DATEADD(yy, DATEDIFF(yy,0,[Id-rent_date]) + @iter, 0)
,DATEADD(yy, DATEDIFF(yy,0,[Id-rent_date]) + 1 + @iter, -1)
,IdCar
FROM Renting
where year([Id-rent_date]) + @iter <> year(Car_return_date) and year([Id-rent_date]) <> year(Car_return_date)
set @iter = @iter + 1
END
SELECT YEAR([Id-rent_date]), SUM(DATEDIFF(dd, [Id-rent_date], Car_return_date)) AS Days,
Company
FROM
(SELECT
[Id-rent_date]
,[Car_return_date]
,IdCar
FROM Renting
where year([Id-rent_date]) = year(Car_return_date)
union all
SELECT
[Id-rent_date]
,DATEADD(yy, DATEDIFF(yy,0,[Id-rent_date]) + 1, -1)
,IdCar
FROM Renting
where year([Id-rent_date]) <> year(Car_return_date)
UNION ALL
SELECT
DATEADD(yy, DATEDIFF(yy,0,[Car_return_date]), 0)
,[Car_return_date]
,IdCar
FROM Renting
where year([Id-rent_date]) <> year(Car_return_date)
UNION ALL
select * from @test) RentingSplit inner join Cars ON RentingSplit.IdCar = Cars.IdCar
GROUP BY Company, YEAR([Id-rent_date])
我沒想到那個查詢會如此複雜!它工作得很好,謝謝! – 2014-10-22 17:29:41
如果你在現場Car_return_date以NULL值允許(車上沒有得到回報),你應該使用ISNULL(Car_return_date,GETDATE()),而不是Car_return_date。 它應該看起來像SUM(DATEDIFF(DD,[ID-rent_date],ISNULL(Car_return_date,GETDATE()))) – steryd 2014-10-22 17:52:59