我在CheckLine表中有信息,它基本上分解了特定支票的各种费用和信息。对于此查询,我想要求清除CheckLine的总数,但它会为所有CheckLines一起提供SUM。我知道我错过了一些显而易见的东西,但我一直在摸不着为什么要个性化SUMs。这是我的疑问:
SELECT DISTINCT
O.FileNumber
,(SELECT DISTINCT
SUM(CL.Amount)
FROM
dbo.Orders O
LEFT JOIN dbo.Checks C
ON O.OrdersID = C.OrdersID
LEFT JOIN dbo.CheckLine CL
ON C.ChecksID = CL.ChecksID
) AS 'Total'
FROM
dbo.Orders O
LEFT JOIN dbo.Checks C
ON O.OrdersID = C.OrdersID
LEFT JOIN dbo.CheckLine CL
ON C.ChecksID = CL.ChecksID
这就是它的回归:
| FileNumber | … | Total |
| 1 | | 2000 |
| 2 | | 2000 |
它应该返回的是:
| FileNumber | … | Total |
| 1 | | 700 |
| 2 | | 1300 |
关于我完整的大脑放屁的想法?谢谢你们!
答案 0 :(得分:0)
你可能想要这个:
SELECT O.FileNumber, SUM(CL.Amount) as total
FROM dbo.Orders O
LEFT JOIN dbo.Checks C
ON O.OrdersID = C.OrdersID
LEFT JOIN dbo.CheckLine CL
ON C.ChecksID = CL.ChecksID
group by O.FileNumber
答案 1 :(得分:0)
SELECT
O.FileNumber,
O.CloseDate,
SUM(CL.Amount) as Total
FROM dbo.Orders O
LEFT JOIN dbo.Checks C
ON O.OrdersID = C.OrdersID
LEFT JOIN dbo.CheckLine CL
ON C.ChecksID = CL.ChecksID
GROUP BY O.FileNumber, O.CloseDate
在子查询中计算Total
时,SQL Server会将该值视为常量,将重复每一行。
将GROUP BY
与DISTINCT
混淆是很常见的(请查看here和here),因为如果SELECT
中没有聚合函数,它们会返回相同的值{1}}条款。在您的示例中:
SELECT DISTINCT FileNumber FROM ORDERS
将返回相同的
SELECT FileNumber FROM ORDERS GROUP BY FileNumber
如果您想要汇总信息(例如您的字段GROUP BY
),请使用TOTAL
。