我有一个返回表的函数。我的左连接表中有一个字段,该字段导致某些结果重复。 这导致总计错误。我需要以这种方式显示它,因为它已在另一个应用程序的CSV结果中使用。
Job Number | Job Total | Supp Ref (from a Left joined Table)
---------------------------------------------------------------------
4556 101.60 I450666
4556 101.60 P500694
4557 67.70 I88950A
4558 83.15 595900339
4559 132.00 O9995044
4559 132.00 I554112
4559 132.00 33209A00
4559 132.00 669554
Create Function JobDetails
{
... <Bunch of Params>
...
@JobDate DateTime
}
Returns Table
as
Return
Select
JOBNUMBER,
JOBTOTAL,
SUPPREF
from
(Select J.JOBNO as JOBNUMBER, Sum(J.TOTAL) as JobTotal,
S.REFNO = SUPPREF
from
JOBS J Left Join
JOBNOTES S on J.ID = S=JOBID
Where J.DATE >=@JobDate
Group by J.JOBNO, S.REFNO
) as JobTotals
我希望看到的是
Job Number | Job Total | Supp Ref (from a Left joined Table)
---------------------------------------------------------------------
4556 101.60 I450666
4556 P500694
4557 67.70 I88950A
4558 83.15 595900339
4559 132.00 O9995044
4559 I554112
4559 33209A00
4559 669554
我知道这是有可能的,但是我不确定该怎么做。 感谢您的帮助。
答案 0 :(得分:2)
首先,您的子查询不是必需的:
Select J.JOBNO as JOBNUMBER, Sum(J.TOTAL) as JobTotal,
S.REFNO as SUPPREF
from JOBS J Left Join
JOBNOTES S
on J.ID = S.JOBID
Where J.DATE >= @JobDate
Group by J.JOBNO, S.REFNO
您可以使用窗口功能执行所需的操作:
Select J.JOBNO as JOBNUMBER,
(CASE WHEN row_number() over (partition by J.JOBNO order by S.REFNO) = 1
THEN Sum(J.TOTAL)
END) as JobTotal,
S.REFNO as SUPPREF
from JOBS J Left Join
JOBNOTES S
on J.ID = S.JOBID
Where J.DATE >= @JobDate
Group by J.JOBNO, S.REFNO