SQL使用附加的sum列创建视图

时间:2014-11-24 16:44:45

标签: sql-server

您好我正在尝试从两个不同的表创建一个视图,该表有一个额外的列,它是Table1.Price1 - Table2.Price2的总和。没有附加列的视图是:

Create View testview AS (
SELECT t1.ID,t1.Price1,t2.Price2 FROM
Table1 t1
LEFT JOIN
Table2 t2
ON
t1.ID = t2.ID
);

非常感谢任何帮助,谢谢。

下面是视图的外观表示:

ID    | Table1.Price1 | Table2.Price2 | Total | 
---------------------------------------   
1 | 15.00       | 5.00  | 10.00    |

2 | 10.00       | 2.50  | 7.50     |

3 个答案:

答案 0 :(得分:2)

试试这个:

Create View testview AS 
(SELECT t1.ID,t1.Price1,t2.Price2, (t1.Price1 - t2.Price2) as difference
FROM Table1 t1 
LEFT JOIN Table2 t2 
ON t1.ID = t2.ID );

答案 1 :(得分:0)

只需添加SUM列,如下所示:

Create View testview AS (
SELECT t1.ID,t1.Price1,t2.Price2, t1.Price1-t2.Price2 AS [SUM] FROM
Table1 t1
LEFT JOIN
Table2 t2
ON
t1.ID = t2.ID
);

答案 2 :(得分:0)

您可以使用+, - ,*,/运算符添加两列,如:

Create View testview AS (
   SELECT t1.ID,t1.Price1,t2.Price2, t1.Price1+t2.Price2 as total FROM
   Table1 t1
   LEFT JOIN
   Table2 t2 ON t1.ID = t2.ID
);

这将产生您想要的表格结构