2017-12-10 5 views
0

私は、SQL Server 2014を使用していますが、私はTable1としてデータベースに保存されている次の出力を返しますT-SQLクエリを持っている:このテーブルの値を特定のロジックに基づいて特定のフォーマットに変換する方法はありますか?

Id  AdultCount Adult1Age C1-5 C6-12 C13-17 
--------------------------------------------------- 
101  2   45   1  0  0 
102  1   36   0  0  0 
103  2   40   0  2  1 

私は以下のロジックでT-SQLクエリを記述する必要があります。

  1. カラムAdult1Ageは、大人1人の年齢です。大人が1人以上の場合、残りの大人は既存のAdult1Age - 2を持ちます(つまり、ID 101の場合、他の大人はAge = 45-2 = 43になります)

  2. カラムC1-5,C6-12,C13-17は、これらの年齢層のそれぞれについての子供のカウントを提供する。つまり、C1-5は1歳から5歳の子供の数を表します。カテゴリの下限と上限を使用して、子供の平均年齢(中間点)を計算します。したがって、もし私がC1-5の下に1人いるなら、その子供は年齢=(1 + 5)/ 2 = 3を持つでしょう。

    私たちはID 103を見ると9歳の子供が2人15歳の子供。私はこれについて移動するにはどうすればよい

    Id  Age 
    ---------- 
    101 45 
    101 43 
    101  3 
    102 36 
    103 40 
    103 38 
    103  9 
    103  9 
    103 15 
    

は今、私は次のような出力を返すために、表1で実行されているT-SQLクエリを必要としますか?

答えて

0

次のコマンドを実行します。

declare @tab table (Id int, AdultCount int, AdultAge int, [C1-5] int, [C6-12] int, [C13-17] int) 
insert into @tab 
select 101,2,45,1,0,0 
union 
select 102,1,36,0,0,0 
union 
select 103,2,40,0,2,1 

select * from @tab 

declare @t table (Id int) 
insert into @t select distinct Id from @tab 

while ((select count(1) from @t) > 0) 
begin 
    declare @Id int = (select top 1 Id from @t) 
    declare @age_tab table (Id int, Age int) 
    declare @cage1 smallint = 3, @cage2 smallint = 9, @cage3 smallint = 15 
    declare @i_a int = (select AdultCount from @tab where Id = @Id) 
    declare @i_c1 int = (select [C1-5] from @tab where Id = @Id) 
    declare @i_c2 int = (select [C6-12] from @tab where Id = @Id) 
    declare @i_c3 int = (select [C13-17] from @tab where Id = @Id) 
    declare @age int = (select AdultAge from @tab where Id = @Id) 

    while (@i_a>1) 
    begin 
     insert into @age_tab select @Id, (@age - 2) 
     set @age-=2 
     set @i_a-=1 
    end 

    while (@i_c1>0) 
    begin 
     insert into @age_tab select @Id, @cage1 
     set @i_c1-=1 
    end 
    while (@i_c2>0) 
    begin 
     insert into @age_tab select @Id, @cage2 
     set @i_c2-=1 
    end 
    while (@i_c3>0) 
    begin 
     insert into @age_tab select @Id, @cage3 
     set @i_c3-=1 
    end 
    insert into @age_tab select Id, AdultAge from @tab where Id = @Id 

    delete @t where Id = @Id 
end 

select * from @age_tab 
order by Id, age desc 

HTH!

ありがとうございました。

+0

素晴らしい!どうもありがとう! – user3115933

関連する問題