我需要帮助根据列值生成SQL结果以计算每日金额。
我有一个如下的SQL。
select guid, reccharge, dayCareDaysCharged, dayCareHoursPerDay, RATE from tableA.
如果reccharge = 0(每周),那么结果应该有7行,每行RATE为RATE / 7(每天数量); 如果reccharge = 1(每月),那么结果应该有30行,每行的RATE为RATE / 30; 如果reccharge = 2(每年),那么结果应该有365行,每行的RATE为RATE / 365; 如果reccharge = 3(每小时)那么应该有一行计算一天;
我怎样才能做到这一点。请帮忙。
答案 0 :(得分:0)
我不知道在单个查询中执行此操作,但您可以使用CURSOR执行此操作,如下所示:
declare @reccharge int
declare @count int
declare @i int
declare @strSQL nvarchar(max) = 'select 1, 1 where 1 <> 1'
declare CurTest cursor for select reccharge from test
open CurTest
fetch next from CurTest into @reccharge
while @@fetch_status = 0
begin
set @i = 0;
select @count = case when @reccharge = 0 then 7 when @reccharge = 1 then 30 when @reccharge = 2 then 365 else 1 end
while @i < @count
begin
set @strSQL = @strSQL + ' union all select reccharge, Rate/' + cast(@count as varchar(10)) + ' from test where reccharge = ' + cast(@reccharge as varchar(10))
set @i = @i + 1;
end
fetch next from CurTest into @reccharge
end
close CurTest
deallocate CurTest
exec(@strSQL)
答案 1 :(得分:0)
这个问题对我来说似乎有点奇怪,但如果我正确地遵循它,那么也许这就是
CREATE TABLE [#temp1] (reccharge tinyint,rdays smallint)
GO
declare @rcount smallint
set @rcount=0
while @rcount<7
begin
set @rcount=@rcount+1
insert #temp1 values (0,7)
end
set @rcount=0
while @rcount<30
begin
set @rcount=@rcount+1
insert #temp1 values (1,30)
end
set @rcount=0
while @rcount<365
begin
set @rcount=@rcount+1
insert #temp1 values (2,365)
end
insert #temp1 values (3,1)
GO
select t1.[guid], t1.reccharge, t1.dayCareDaysCharged, t1.dayCareHoursPerDay, t1.RATE/t2.rdays as RATE from tableA t1
inner join #temp1 t2 on t1.reccharge=t2.reccharge
order by t1.[guid]