SQL Server视图 - 从规范化源模拟表

时间:2011-04-15 21:16:05

标签: sql-server view union normalize

好吧,我有一张桌子需要存放在数据库中。该表格式如下:

Value  | No Deductible | $100 | $250 | $500 |
=============================================
$20000 |          $122 |  $61 |  $28 |  N/A |
$30000 |          $183 | $117 |  $67 |  $44 |

为了使其规范化且易于访问,该表将在SQL Server数据库中采用以下格式:

Value (PK)  | Deductible (PK) | Cost |
======================================
     $20000 |              $0 | $122 | 
     $20000 |            $100 |  $61 |  

ValueDeductible列是联合主键,可防止重复。此外,还有一个约束只允许某些可扣除的值。

现在,这种格式非常适合可访问性,但显然不容易插入数据。我没有立即为它构建逻辑前端的计划,因此在这种情况下的视图将是理想的。但是,我尝试生成一个我可以轻松编辑的视图失败了。

尝试1

SELECT 
    t1.Value, t2.Cost AS [No Deductible], 
    t3.Cost AS [$100], t4.Cost AS [$250], t5.Cost AS [$500]
FROM  Valuation AS t1 
INNER JOIN Valuation AS t2 ON t1.Value = t2.Value 
INNER JOIN Valuation AS t3 ON t2.Value = t3.Value 
INNER JOIN Valuation AS t4 ON t3.Value = t4.Value 
INNER JOIN Valuation AS t5 ON t1.Value = t5.Value
WHERE  
    (t2.Deductible = 0) AND (t3.Deductible = 100) 
    AND (t4.Deductible = 250) AND (t5.Deductible = 500)  

这不起作用,因为您无法修改多个基表。

尝试2

SELECT Value, 
   (SELECT Cost FROM Valuation WHERE Deductible = 0) AS [No Deductible],
   (SELECT Cost FROM Valuation WHERE Deductible = 100) AS [$100],
   (SELECT Cost FROM Valuation WHERE Deductible = 250) AS [$250],
   (SELECT Cost FROM Valuation WHERE Deductible = 500) AS [$500]
FROM Valuation 
GROUP BY Value

您也无法修改计算列。

这个问题有优雅的解决方案吗?也许与工会有关?我觉得我现在唯一的解决方案是为每个免赔额生成多个视图,保留原始表格布局(可能但不是首选,因为值/免赔额键在其他表格中用作外键)或者只是投资创建逻辑前端以模拟表格的时间(正如我所说,我希望稍后再做)。

1 个答案:

答案 0 :(得分:1)

查询的另一个选择是:

Select Value
    , Min( Case When Deductible = '0' Then Cost End ) As [No Deductible]
    , Min( Case When Deductible = '100' Then Cost End ) As [$100]
    , Min( Case When Deductible = '250' Then Cost End ) As [$250]
    , Min( Case When Deductible = '500' Then Cost End ) As [$500]
From Valuation
Group By Value

但是,这不会使视图可更新。使其可更新的唯一方法是添加一个WaitOf触发器,该触发器将视图结构中的输入行重新规范化为其标准化存储格式。