[英]SQL GROUP BY on a sub query
我有一个查询,将使用UNION ALL将2个表的结果返回到1,这些都可以根据需要进行操作。 但是我需要在返回的数据集上运行GROUP BY和ORDER BY,但是我遇到了很多错误,我不知道如何解决它。
这是我的查询:
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
这将返回一个结果集,如下所示:
ProductID Quantity
15 2
20 2
15 1
8 5
5 1
然后,我想在ProductID
字段上运行GROUP BY
,最后在Quantity
字段上运行ORDER BY DESC
。 所以在最终输出中,这个特定的结果集最终会导致:
ProductID
8
15
20
5
然后,我可以像往常一样对此结果集运行查询
编辑:
如上所述,但可能没有暗示我将需要对返回的结果运行查询,这不起作用,因为您无法对具有ORDER BY子句的一组结果运行查询(就我收集而言)来自错误列表)
如果您想了解有关该问题的更多信息,请点击此处:
从这个结果集中,我想从产品表中获取与之相关的产品
SELECT * FROM Products WHERE ID IN (
SELECT ProductID
FROM
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) v
GROUP BY ProductID
ORDER BY SUM(Quantity) DESC
)
但是,我收到此错误:ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP,OFFSET或FOR XML。
产品的输出必须按照它们在子查询中返回的顺序(按数量)
SELECT Products.*
FROM Products
INNER JOIN
(
SELECT ProductID, Sum(Quantity) as QuantitySum
from
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) v
GROUP BY ProductID
) ProductTotals
ON Products.ID = ProductTotals.ProductID
ORDER BY QuantitySum DESC
这会有用吗?
SELECT ProductID
from
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) temp
GROUP BY temp.ProductID
ORDER BY SUM(temp.Quantity) desc
这是一个cte版本(没有现场测试,所以请原谅错误)
编辑
;WITH myInitialdata_cte(ProductID,Quantity)
AS
(
SELECT ProductID, Quantity FROM BasketItems
UNION ALL
SELECT ProductID, Quantity FROM OrderItems
)
SELECT b.ID
FROM
myInitialdata_cte a
INNER JOIN Products b ON
a.ProductID = b.ID
GROUP BY ProductID
ORDER BY SUM(a.Quantity) DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.