问题连接SQL表与包含行号集合函数的语句

在Excel中使用SQL,我创build了一个语句来拉和连接logging使用以下职位作为指导SQL 2008将具有相同ID的多个行的数据合并到一行 (我的答案)我无法弄清楚如何join一个额外的表格现在。 我想我只是把它添加到错误的领域。

这是工作代码:

sql = sql & "select REPID, ReportDate, " sql = sql & "max(case when CategoryID = 5001 then Score end) InPercent, " sql = sql & "max(case when CategoryID = 5002 then Score end) OutPercent " sql = sql & "from " sql = sql & "(select REPID, ReportDate, Score, CategoryID, row_number() over(partition by REPID, ReportDate order by Score) rn from REPREPORTING RR Where RepID <> 0) " sql = sql & " d group by REPID, ReportDate " 

这里是我需要添加的联合声明:

 sql = sql & "JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID " 

我通常会把这个放在声明的末尾,并且已经试过了,并且在join这个词的附近得到错误的语法错误。 我也把它放在群组之前,同样的错误。

任何帮助表示赞赏!

我想这是你想要的:

 with d as ( select RR.REPID, RR.ReportDate, RR.Score, RR.CategoryID, row_number() over(partition by RR.REPID, RR.ReportDate order by RR.Score) rn from REPREPORTING RR JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID -- right here Where RR.RepID <> 0 ) select d.REPID, d.ReportDate, max(case when d.CategoryID = 5001 then d.Score end) InPercent, max(case when d.CategoryID = 5002 then d.Score end) OutPercent from d group by d.REPID, d.ReportDate 

为了便于阅读,我把你的子查询d移入了一个CTE中,所以不要太多地阅读。

可以将连接移动到外部查询(d),但在调用分组函数之前删除行效率更高 – 分组需要的行越less,查询运行得越好。

也就是说,一旦我这样做,我不禁会注意到,调用窗口函数的字段看起来没有任何影响。 你的意思是使用这个,也许只取第一行:

 with d as ( select RR.REPID, RR.ReportDate, RR.Score, RR.CategoryID, row_number() over(partition by RR.REPID, RR.ReportDate order by RR.Score) rn from REPREPORTING RR JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID Where RR.RepID <> 0 ) select d.REPID, d.ReportDate, max(case when d.CategoryID = 5001 then d.Score end) InPercent, max(case when d.CategoryID = 5002 then d.Score end) OutPercent from d where d.rn = 1 -- Did you mean to add this? group by d.REPID, d.ReportDate 

如果没有,我认为你完全可以避免CTE /子查询,并消除了窗口函数( row_number ),虽然我最喜欢的函数之一,确实有一些相关的成本:

 select RR.REPID, RR.ReportDate, max(case when RR.CategoryID = 5001 then RR.Score end) InPercent, max(case when RR.CategoryID = 5002 then RR.Score end) OutPercent from from REPREPORTING RR JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID group by RR.REPID, RR.ReportDate 

而且,当然,VBA版本:

 sql = _ "select " & _ " RR.REPID, RR.ReportDate, " & _ " max(case when RR.CategoryID = 5001 then RR.Score end) InPercent, " & _ " max(case when RR.CategoryID = 5002 then RR.Score end) OutPercent " & _ "from " & _ " from REPREPORTING RR " & _ " JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID " & _ "group by " & _ " RR.REPID, RR.ReportDate" 

不能JOIN放在最后。

现在你有:

 SELECT <fields> FROM <subquery> GROUP BY <fields> 

你要么想join子查询

 SELECT <fields> FROM <subquery> s JOIN <anotherTable> t ON s.joinCondition = t.joinCondition GROUP BY <fields> 

或者在子查询中JOIN

 SELECT <fields> FROM <subquery JOIN here> s GROUP BY <fields>