我如何将这3个T-SQL语句合并为一个?

时间:2011-11-06 23:27:51

标签: sql database tsql

我想要组合3个查询。 1个查询用于总销售额,1个用于取消订单,1个用于不包含特定产品类型的订单。只需要以表格格式输出总销售额$$,就像现在一样。 3之间唯一变化的是where语句。谢谢!

编辑:我意识到我说“只需要总销售额”......我的意思是我只需要在一张表中为每个查询提供销售额$$。所以$ x,$ y,$ z ... x是总销售额,y是取消的销售额,z是特定项目的销售额。

SELECT Sum((Items.Total+Items.Shipping)*OrderDetails.Quantity) AS Total
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE ((Promo.OfferType)='Sale') AND ((Items.Date) Between '6/1/2010' And '12/31/2011');

SELECT Sum((Items.Total+Items.Shipping)*OrderDetails.Quantity) AS Canceled
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE (((Promo.OfferType)='Sale') AND ((Items.Date) Between '6/1/2010' And '12/31/2011') AND ((Items.Status)="Canceled"));

SELECT Sum((Items.Total+Items.Shipping)*OrderDetails.Quantity) AS BadItems
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE (((Promo.OfferType)='Sale') AND ((Items.Date) Between '6/1/2010' And '12/31/2011') AND ((Items.ProductType)<>2) AND ((Items.ProductType)<>6));

谢谢!

3 个答案:

答案 0 :(得分:0)

更新以反映问题澄清:

SELECT Sum(CASE WHEN Items.Status <> 'Canceled' AND Items.ProductType = 4 THEN (Items.Total+Items.Shipping)*OrderDetails.Quantity ELSE 0 END) AS Total ,
       Sum(CASE WHEN Items.Status = 'Canceled' AND Items.ProductType = 4 THEN (Items.Total+Items.Shipping)*OrderDetails.Quantity ELSE 0 END) AS Canceled,
       Sum(CASE WHEN Items.ProductType <> 4 THEN (Items.Total+Items.Shipping)*OrderDetails.Quantity ELSE 0 END) AS BadItems,
FROM Promo INNER JOIN (Orders INNER JOIN (Items INNER JOIN OrderDetails ON Items.ItemCode = OrderDetails.ItemCode) ON Orders.OrderNumber = OrderDetails.OrderNumber) ON Promo.Promo = Orders.Promo
WHERE ((Promo.OfferType)='Sale') AND ((Items.Date) Between '9/1/2010' And '12/31/2010');

答案 1 :(得分:0)

如果您想将结果放在第1行:

SELECT Total, Canceled, BadItems
FROM Query1, Query2, Query3

如果您想将结果放在1列中,请使用UNION

Query1
UNION
Query2
UNION
Query3

答案 2 :(得分:0)

尝试使用一个接受三个值作为输入的过程,这个过程将对你的be语句进行套接,并且它会在一个表中给出结果。如果你被困住让我知道,我会帮助你。