SQL创建一个额外的总和列的视图

问题描述:

您好我试图从两个不同的表中创建一个视图有一个额外的列是Table1.Price1 - Table2.Price2的总和。没有额外的列视图是:SQL创建一个额外的总和列的视图

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  | 
+2

'选择.... T1.Price2-T2.Price2作为总FROM 表1 T1 LEFT JOIN 表2 T2 ON t1.ID = T2。 ID' – 2014-11-24 16:47:53

试试这个:

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); 

只需添加您的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 
); 

你可以使用+, - ,*,/运算符添加两列,如下所示:

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 
); 

这将导致所需的表结构