有没有办法在select子句中不重复此子查询? SQL Server

时间:2018-07-18 15:54:10

标签: sql sql-server

是否可以以以下查询语法重复子查询?

如您所见,我在Select子句中将总计算作为最终价格和各个零件。

我正在使用SQL Server。

SELECT        
    ItemPrice.ItemID, 
    COALESCE( ItemPrice.MetalPrice, 0 ) + COALESCE(
    (SELECT SUM( PartsPrice.PartPriceTotal )
     FROM PartsPrice
     WHERE ItemPrice.ItemID = PartsPrice.ItemID
     GROUP BY PartsPrice.ItemID), 0) AS FinalItemPrice,
    ItemPrice.MetalPrice,
    (SELECT SUM(PartsPrice.PartPriceTotal)
     FROM PartsPrice
     WHERE ItemPrice.ItemID = PartsPrice.ItemID
     GROUP BY PartsPrice.ItemID) AS PartTotalPrice
FROM
    ItemPrice 
WHERE
    ItemPrice.ItemID = '100456'
GROUP BY
    ItemPrice.MetalPrice, 
    ItemPrice.ItemID

4 个答案:

答案 0 :(得分:2)

一种方法是使用FROMAPPLY子句中使用子查询:

SELECT I.ItemID,
       COALESCE(I.MetalPrice, 0) + PT.Total AS FinalItemPrice,
       I.MetalPrice,
       PT.Total AS PartTotalPrice
FROM ItemPrice I
     CROSS APPLY (SELECT SUM(PP.PartPriceTotal) AS Total
                  FROM PartsPrice  PP
                  WHERE I.ItemID = PP.ItemID
                  GROUP BY PP.ItemID) PT
WHERE I.ItemID = '100456'
GROUP BY I.MetalPrice,
         I.ItemID;

但是,看起来您根本不需要使用子查询,使用适当的聚合和JOIN语法:

SELECT I.ItemID,
       COALESCE(I.MetalPrice, 0) + SUM(PP.PartPriceTotal) AS FinalItemPrice,
       I.MetalPrice,
       SUM(PP.PartPriceTotal) AS PartTotalPrice
FROM ItemPrice I
     JOIN PartsPrice PP ON I.ItemID = PP.ItemID
WHERE I.ItemID = '100456'
GROUP BY I.MetalPrice,
         I.ItemID;

当然,在没有样本数据的情况下,这两个都未经测试。我还假设每个ItemPrice都有一个PartPrice。如果不是,则分别需要分别使用OUTER APPLYLEFT JOIN

答案 1 :(得分:2)

dp

答案 2 :(得分:1)

使用联接:

SELECT        
    ItemPrice.ItemID, 
    COALESCE (ItemPrice.MetalPrice, 0) + COALESCE (t2.partpricetotal, 0) AS FinalItemPrice,
    ItemPrice.MetalPrice, 
    t2.PartTotalPrice
FROM ItemPrice 
    LEFT OUTER JOIN (SELECT ItemID, SUM(PartsPrice.PartPriceTotal) as PartPriceTotal FROM PartsPrice GROUP BY PartsPrice.ItemID) t2
        ON ItemPrice.ItemID = PartsPrice.ItemID
WHERE ItemPrice.ItemID = '100456'

答案 3 :(得分:1)

使用内部子查询(在FROM子句中)。通常,SELECT子句中不应包含子查询:

SELECT        
    ItemPrice.ItemID, 
    COALESCE( ItemPrice.MetalPrice, 0 ) + COALESCE( sq.PartPriceTotal, 0 ) AS FinalItemPrice,
    ItemPrice.MetalPrice,
    COALESCE( sq.PartPriceTotal, 0 ) AS PartTotalPrice
FROM
    ItemPrice
    LEFT OUTER JOIN
    (
        SELECT
            PartsPrice.ItemID,
            SUM( PartsPrice.PartPriceTotal )
        FROM
            PartsPrice
        GROUP BY
            PartsPrice.ItemID
    ) AS sq ON ItemPrice.ItemID = sq.ItemID
WHERE
    ItemPrice.ItemID = '100456'
GROUP BY
    ItemPrice.MetalPrice, 
    ItemPrice.ItemID