次のようなユニオンセレクトクエリをもっと簡潔に書くことは可能ですか?
select
id,
1,
(1 + @defCapUp) * (p.Value + p.Premium),
getdate()
from Products p
union
select
id,
1,
(1 - @defCapDown) * (p.Value - p.Premium),
getdate()
from Products p
union
select
id,
case when p.Paydate > getdate() then 1 else 0 end,
(1 - @defCapUp) * (p.Value - p.Premium),
@nextYear
from Products p
union
select
id,
case when p.Paydate > getdate() then 1 else 0 end,
(1 + @defCapDown) * (p.Value + p.Premium),
@nextYear
from Products p
このステートメントは、Productsテーブルの各行に対して4つの行を選択します。変化するのは、列2とツリーの値を計算するために使用される式だけです。それほど醜いコードの重複なしに上記を書く方法がSQLにあるべきだと思います。関数のみがファーストクラスのオブジェクトであり、SQLでラムダ式が許可されている場合...
以下のリチャードのソリューションは完璧であり、提供された例では非常にうまく機能します。しかし、元の例では2つのタイプミスがあり、問題がやや難しくなっています。
select
id,
1,
(1 + @defCapUp) * (p.Value + p.Premium),
getdate()
from Products p
union
select
id,
1,
(1 - @defCapDown) * (p.Value - p.Payout),
getdate()
from Products p
union
select
id,
case when p.Paydate > getdate() then 1 else 0 end,
(1 - @defCapUp) * (p.Value - p.Premium),
@nextYear
from Products p
union
select
id,
case when p.Paydate <= getdate() then 1 else 0 end,
(1 + @defCapDown) * (p.Value + p.Payout),
@nextYear
from Products p
大きな問題は、比較演算子が異なるケース式です。私の問題は、これらのケースを「きちんと」処理することが非常に難しいことです。たとえば、比較がp.Paydate = getdate()である3番目のケースがあった場合はどうなりますか?