我有一个(工作)查询,看起来有点像:
SELECT DISTINCT
Convert(Varchar(150),O.PONumber) AS OrderID,
CONVERT(varchar, O.OrderDateTime, 111) AS OrderDateTime,
CONVERT(varchar, DATEADD(DAY, 14, O.OrderDateTime), 111) AS DateExpire,
C.ClientID,
C.ClientName,
U.FirstName + ' ' + U.LastName AS Name
...
我想在此添加类似内容:
(SELECT
SUM((
SELECT
OI.UnitPoints
FROM
Orders O INNER JOIN
[dbo].[OrderItems] AS OI ON O.OrderID = OI.OrderID
WHERE
O.PONumber = 72084))) AS TotalPoints
由此返回的值:
SELECT
OI.UnitPoints
FROM
Orders O INNER JOIN
[dbo].[OrderItems] AS OI ON O.OrderID = OI.OrderID
WHERE
O.PONumber = 72084
看起来像这样:
UnitPoits
---------
1
2
所以在这个特定的实例中,我正在寻找分配给TotalPoints的值为3(1 + 2)。
答案 0 :(得分:0)
您可以使用GROUP BY
语句来实现此目的:
SELECT
O.OrderID,
SUM(OI.UnitPoints) as TotalPoints
FROM
Orders O INNER JOIN
[dbo].[OrderItems] AS OI ON O.OrderID = OI.OrderID
WHERE
O.PONumber = 72084
GROUP BY O.OrderID