来自同一个表的数据与不同的where子句进入相同的视图

时间:2016-10-11 12:36:19

标签: sql-server

我正在尝试将同一个表中的两种数据放入视图中。我尝试使用不同的别名向同一个表添加连接,但它会导致一些空值。

如果可能的话,我想将数据表作为单行。我知道这可以通过union运算符完成,但它会导致多行。

这是我的选择

SELECT 
COUNT(PO.OrderID) AS MerkezOnaySiparisAdet, SUM(PO.TotalPromotionPrice) AS MerkezOnayToplamSatis,
COUNT(PO2.OrderID)  AS DepoOnaySiparişAdet, SUM(PO2.TotalPromotionPrice) AS DepoOnayToplamSatis
FROM PrmOrder PO

LEFT JOIN PrmOrder PO2 ON PO.OrderID = PO2.OrderId AND (PO2.OrderStatusID != 1 AND PO2.IsOrderApproved = 1 AND PO2.IsInventoryApproved = 0 AND (PO2.OrderStatusID = 2 OR PO2.OrderStatusID = 3))

WHERE 1=1
AND PO.OrderStatusID != 1
AND PO.IsOrderApproved = 0
AND (PO.OrderStatusID = 2 OR PO.OrderStatusID = 3)

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

也许,这不是最好的方法,但你可以使用子查询。例如

   SELECT 
 A1.Sum1,
 A2.Sum2 FROM   
 (
   SELECT 
     SUM(sod.OrderQty) sum1,
     1 joinnumber
   FROM   
     Sales.SalesOrderDetail sod
   WHERE  
     sod.ProductID = 772
 ) AS A1
   JOIN (
          SELECT 
            SUM(sod.OrderQty) sum2,
            1 joinnumber
          FROM   
            Sales.SalesOrderDetail sod
          WHERE  
            sod.ProductID = 773
        ) AS A2
     ON A1.joinnumber = A2.joinnumber