帮助SQL视图涉及SUM函数

时间:2010-02-23 15:58:55

标签: sql

我想将以下数据(以及更多)放入单个视图中。

SELECT Price FROM dbo.OrderItems WHERE OrderItemTypeId = 0 

并且

SELECT SUM (Price) AS ShippingTotal FROM dbo.OrderItems WHERE OrderItemTypeId = 1

我似乎无法弄清楚如何使用我的弱SQL技能来做到这一点。谁知道我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

您可以使用UNION语句:

SELECT Price FROM dbo.OrderItems WHERE OrderItemTypeId = 0 

UNION

SELECT SUM (Price) AS ShippingTotal FROM dbo.OrderItems WHERE OrderItemTypeId = 1

但是这背后的语义是什么......在第一个语句中你只有一行id = 0,第二个是由同一列分组的聚合函数(假设有多个记录带有id = 1)。向我们展示您的表格样本数据会很有帮助。

要提高您对UNION的技能,请参阅此处:http://www.w3schools.com/sql/sql_union.asp

答案 1 :(得分:1)

涵盖所有OrderItemTypeId ...

SELECT OrderItemTypeId, SUM(Price) AS ShippingTotal
FROM dbo.OrderItems 
GROUP BY OrderItemTypeId 

答案 2 :(得分:0)

一种方式是这样的:

SELECT Price, 0 AS OrderItemTypeId FROM dbo.OrderItems WHERE OrderItemTypeId = 0 
UNION ALL
SELECT SUM(Price) AS Price, 1 AS OrderItemTypeId FROM dbo.OrderItems 
WHERE OrderItemTypeId = 1

我添加到结果中的第二列允许您确定不同的行。