这个查询对我来说很好。
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 | ItemSold | TotalSale
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引入子查询时,只能在选择列表中指定一个表达式。
我知道我正在越过极限,但有没有其他方法可以做到这一点。 我知道可以创建该功能来完成这项任务。但是创造至关重要 三个功能分别计算这些总平均价格,商品销售,总销售? 虽然我相信一个查询可以为我计算三个聚合? 任何人都可以建议我妥善解决?我只想分别为这些聚合创建三个函数。 问候。
答案 0 :(得分: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
答案 1 :(得分: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