请帮忙。
我想让我的代码对每个[CTN]列出的[值]求和。我相信代码只将SUM聚合函数应用于[Values],每个[CTN]都是相同的,因此有超过1个[CTN]。
示例表(我无法发布图片)粗体=行号/ 2列/使用'。'将列对齐,以便它们对齐:
我希望看到:
我的代码:
USE AdventureWorks2012;
GO
SELECT y.CTN
,SUM(y.[Value]) AS 'Total'
FROM(
SELECT CarrierTrackingNumber AS 'CTN'
,SalesOrderDetailID AS 'Orders'
,[Value] = UnitPrice*OrderQty
FROM Sales.SalesOrderDetail
WHERE CarrierTrackingNumber IS NOT NULL
) AS y
GROUP BY CTN, Value
HAVING Value > 4000
ORDER BY CTN
答案 0 :(得分:0)
您需要从value
中删除group by
并修复having
子句。此外,子查询是不必要的:
SELECT CarrierTrackingNumber, SUM(UnitPrice*OrderQty) AS Total
FROM Sales.SalesOrderDetail
WHERE CarrierTrackingNumber IS NOT NULL
GROUP BY CarrierTrackingNumber
HAVING Total > 4000
ORDER BY CarrierTrackingNumber;
<强> RESPONSE /结论:强>
我的代码现在(使用添加) 子查询存在,因为我误解了一个错误,我认为无法对计算列进行求和:
SELECT CarrierTrackingNumber
,COUNT(CarrierTrackingNumber) AS 'Count'
,SUM(UnitPrice*OrderQty) AS 'Total'
FROM Sales.SalesOrderDetail
WHERE CarrierTrackingNumber IS NOT NULL
GROUP BY CarrierTrackingNumber
ORDER BY CarrierTrackingNumber ASC