0

是否可以更简洁地编写如下的联合选择查询?

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 表中的每一行选择四行。唯一不同的是用于计算第二列和树的值的公式。我认为在 sql 中应该有一种方法可以编写上述内容,而不会出现太多丑陋的代码重复。如果只有函数是第一类对象并且 sql 允许 lambda 表达式...

下面理查德的解决方案非常完美,非常适合提供的示例。但是我在原始示例中有两个拼写错误,这使问题变得更加棘手:

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

最大的问题是比较运算符不同的 case 表达式。我的问题是很难“整齐”地处理这些案件。如果有第三种情况,例如比较是 p.Paydate = getdate() 怎么办?

4

2 回答 2

3

(不确定 lambda 表达式会如何帮助您)

select
    id,
    case when p.Paydate > X.CompareDate then 1 else 0 end,
    (1 + Cap) * (p.Value + ModF * p.Premium),
    @nextYear
from Products p
cross join (
    select @defCapUp Cap, Cast(0 as datetime) CompareDate, 1 Modf union all
    select -@defCapDown, 0, -1 union all
    select -@defCapUp, GETDATE(), -1 union all
    select @defCapDown, GETDATE(), 1
    ) X

顺便说一句,您应该一直使用 UNION ALL,而不是 UNION。

于 2011-03-03T18:53:32.770 回答
0

如果顺序无关紧要,您可以使用WHERE.

SELECT id, field2, field3, field4
FROM Products p
WHERE (
  field4 = getdate() AND field2=1 AND
  (
    field3=(1 + @defCapUp) * (p.Value + p.Premium) OR
    field3=(1 - @defCapDown) * (p.Value - p.Premium)
  )
)
OR
(
  field4=@nextYear AND field2=(case when p.Paydate > getdate() then 1 else 0 end) AND
  (
    field3=(1 - @defCapUp) * (p.Value - p.Premium) OR
    field3=(1 + @defCapDown) * (p.Value + p.Premium)
  )
)
于 2011-03-03T19:20:10.020 回答