我为报告目的进行了查询,以列出尚未提交季度报告的雇主并列出尚未提交的季度。这是我的查询:
with employerIds as (select distinct Employerid
from employerTransaction),
quarters as (select distinct QId
from employerTransaction)
select ei.EmployerId, e.EmployerName, q.QId
from employerIds as ei
cross join quarters as q
left join employerTransaction as et
on et.EmployerId = ei.EmployerId
and et.QId = q.QId
join employer as e
on e.EmployerId = ei.EmployerId
where et.employerid is null
group by ei.employerid, q.QId
order by ei.EmployerId, q.QId
以下是查询结果:
EmployerId EmployerName QId
1 Potato Inc 20193
1 Potato Inc 20202
1 Potato Inc 20203
2 Donuts LLC 20202
2 Donuts LLC 20203
3 Pineapple Logistics 20191
3 Pineapple Logistics 20192
3 Pineapple Logistics 20193
3 Pineapple Logistics 20194
我想要的是将 QId 列合并为每个 EmployerId 的一行,如下所示:
EmployerId EmployerName QId
1 Potato Inc 20193, 20202, 20203
2 Donuts LLC 20202, 20203
3 Pineapple Logistics 20191, 20192, 20193, 20194
我正在使用 Sql Server 2016,所以很遗憾我无法利用string_agg()
并且必须使用FOR XML
和stuff()
. 我不确定如何stuff()
在具有多个连接的查询上使用。任何帮助表示赞赏。