我有一个SQL查询:
Select Top 3 dbo.FN_GetLRExpenseAmount(VendorBillID,LRNo,PM.PickupRunsheetNo)
From PickupRunsheetMaster PM Left Outer Join
PickupRunsheetDetail PRD
ON PM.PickupRunsheetNo = PRD.PickupRunsheetNo
Where ISNULL(VendorBillID,0) > 0
输出:
601.90
14.56
145.62
当我将函数dbo.FN_GetLRExpenseAmount(VendorBillID,LRNo,PM.PickupRunsheetNo)
的返回值加到查询下面时,它就不会返回任何值
Select Top 3 SUM(dbo.FN_GetLRExpenseAmount(VendorBillID, LRNo, PM.PickupRunsheetNo))
From PickupRunsheetMaster PM Left Outer Join
PickupRunsheetDetail PRD
ON PM.PickupRunsheetNo = PRD.PickupRunsheetNo
Where ISNULL(VendorBillID,0) > 0
答案 0 :(得分:4)
查询不一样。 TOP 3
在第二个查询中不执行任何操作,因为它是一个只返回一行的聚合查询。
对于等效查询,请使用子查询或CTE:
select sum(val) as sum_3
from (Select Top 3 dbo.FN_GetLRExpenseAmount(VendorBillID, LRNo, PM.PickupRunsheetNo) as val
From PickupRunsheetMaster PM Left Outer Join
PickupRunsheetDetail PRD
ON PM.PickupRunsheetNo = PRD.PickupRunsheetNo
Where ISNULL(VendorBillID,0) > 0
) x
答案 1 :(得分:1)
TOP 3 SUM为您提供此结果。要获取所需前3个记录的总和值,请创建子查询:
SELECT
SUM(A.Expense)
FROM
(
Select Top 3 dbo.FN_GetLRExpenseAmount(VendorBillID, LRNo, PM.PickupRunsheetNo) AS [Expense]
From PickupRunsheetMaster PM Left Outer Join
PickupRunsheetDetail PRD
ON PM.PickupRunsheetNo = PRD.PickupRunsheetNo
Where ISNULL(VendorBillID,0) > 0
) AS A