SQL2008。我在表中有浮点值,需要重写以下规则集。规则在另一个表中。
但规则是分层的,即 - 我需要对主表中的每一行应用最严格的所有合适规则。
以下是示例...规则表(B和C可以是NULLS)
A B C Value
1 2 3 100
1 2 NULL 80
1 NULL NULL 60
Main Table
A B C Value OverridenValue
1 2 3 1 100
1 2 2 2 80
1 3 1 3 60
3 1 3 4 4 <- no override as no rule found
NULL NULL NULL 5 5 <- no override as no rule found
我需要一个标量函数,即fnGetOverridenValue(@A int,@ B int,@ C int)返回float
答案 0 :(得分:0)
Select m.A, m.B, m.C, m.[Value],
Case
When Not IsNull(r1.Value) Then r1.Value
When Not IsNull(r2.Value) Then r2.Value
When Not IsNull(r3.Value) Then r3.Value
Else m.[Value]
End as Overriddenvalue
From
MainTable m
Left Join RulesTable r1 on m.A=r1.A and m.B=r1.B and m.C=r1.C
Left Join RulesTable r2 on m.A=r2.A and m.B=r2.B and r2.C is NULL
Left Join RulesTable r3 on m.A=r3.A and r3.B is NULL and r3.C is NULL
答案 1 :(得分:0)
在RulesTable中添加一个Priority列,其中第一个规则为1,依此类推。
select top 1 from RulesTable
where A=@A
and (B=@B or @B is null and B is null)
and (C=@C or @C is null and C is null)
order by priority