2

这个查询对我来说很好。

SELECT (SUM(AveragePrice)/COUNT(1)) AS AveragePrice, SUM(ItemsSold) AS ItemSold ,(SUM(AveragePrice * ItemsSold)) AS TotalSale FROM dbo.tbl_ProductSales
WHERE ProductID IN ( SELECT ProductID FROM tbl_ProductPostions WHERE tbl_ProductPostions.SearchID=3 AND SaleDate='2012-02-02 00:00:00.000')
GROUP BY SaleDate 

和这样的结果
AveragePrice | 商品已售出 | 总销售额

10 | 2 | 2000

但是当我像这样嵌入这个查询时

SELECT * ,(SELECT (SUM(AveragePrice)/COUNT(1)) AS AveragePrice, SUM(ItemsSold) AS ItemSold ,(SUM(AveragePrice * ItemsSold)) AS TotalSale FROM dbo.tbl_ProductSales
WHERE ProductID IN ( SELECT ProductID FROM tbl_ProductPostions WHERE tbl_ProductPostions.SearchID=tbl_SearchParameters.SearchID AND SaleDate='2012-02-02 00:00:00.000')
GROUP BY SaleDate )
FROM tbl_SearchParameters  

我遇到了这样的错误。当不使用 EXISTS 引入子查询时,选择列表中只能指定一个表达式。

我知道我正在越界,但有没有其他方法可以做到这一点。我知道可以创建该功能来执行此任务。但是必须分别创建三个函数来计算这些聚合平均价格、已售商品、总销售额?虽然我确信一个查询可以为我计算三个聚合?任何人都可以建议我正确的解决方案吗?我只想分别为这些聚合分别创建三个函数。问候。

4

2 回答 2

1

您可以使用APPLY()运算符

SELECT *
FROM tbl_SearchParameters p
  CROSS APPLY (
               SELECT SUM(AveragePrice/COUNT(1)) AS AveragePrice, 
                      SUM(ItemsSold) AS ItemSold,               
                      SUM(AveragePrice * ItemsSold) AS TotalSale 
               FROM dbo.tbl_ProductSales
               WHERE ProductID IN (SELECT ProductID 
                                   FROM tbl_ProductPostions 
                                   WHERE tbl_ProductPostions.SearchID = p.SearchID           
                                     AND SaleDate='2012-02-02 00:00:00.000')
               GROUP BY SaleDate
               ) o
于 2013-03-19T12:03:03.193 回答
0

尝试删除第二个 SELECT,例如:

SELECT * ,(SUM(AveragePrice)/COUNT(1)) AS AveragePrice, 
           SUM(ItemsSold) AS ItemSold ,
          (SUM(AveragePrice * ItemsSold)) AS TotalSale 
FROM dbo.tbl_ProductSales
WHERE ProductID IN (SELECT ProductID 
                    FROM tbl_ProductPostions 
                    WHERE tbl_ProductPostions.SearchID=tbl_SearchParameters.SearchID 
                    AND SaleDate='2012-02-02 00:00:00.000')
GROUP BY SaleDate )
FROM tbl_SearchParameters
于 2013-03-19T11:09:37.277 回答