SQL Server 2016:用于XML和具有多连接查询的内容
出于报告目的,我提出了一个查询,列出了尚未提交季度报告的雇主以及尚未提交季度报告的雇主。这是我的疑问:SQL Server 2016:用于XML和具有多连接查询的内容,sql,sql-server-2016,stuff,Sql,Sql Server 2016,Stuff,出于报告目的,我提出了一个查询,列出了尚未提交季度报告的雇主以及尚未提交季度报告的雇主。这是我的疑问: with employerIds as (select distinct Employerid from employerTransaction), quarters as (select distinct QId from employerTransaction) select ei.EmployerId, e.Empl
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
我想为每个EmployerId将QId列合并为一行,如下所示:
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\u agg()
,而必须将用于XML
和stuff()
。我不知道如何在具有多个联接的查询上使用stuff()
。感谢您的帮助。尝试此解决方案
Select ei.EmployerId,
e.EmployerName ,
ISNULL(STUFF((Select Distinct ', ' + Cast(QId As Varchar(500))
From employerTransaction As Q
Where et.QId = q.QId
FOR XML PATH('')), 1, 1, ''),'-') As [NewQID]
From employerIds As ei
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, e.EmployerName
这是执行该技巧的xml路径
子句<代码>素材
只需去掉前面的“,”
with sampledata as (
-- your original query here
)
select EmployerId, EmployerName,
stuff( (select ','+ cast(t2.Qid as varchar(5))
from sampledata t2
where t2.EmployerId = t1.EmployerId and t2.EmployerName = t1.EmployerName
for xml path ('')), 1, 1,'') qids
from sampledata t1
group by EmployerId, EmployerName
返回
EmployerId EmployerName qids
1 Potato Inc 20193,20202,20203
2 Donuts LLC 20202,20203
3 Pineapple Logistics 20191,20192,20193,20194
您不需要为此使用STUFF函数。您可以使用FOR XML(子)查询来实现这一点。STUFF函数仅用于通过删除前导(或尾随)分隔符来美化最终结果。如果使用逗号和空格(
,“
)作为分隔符,分隔符长度为2个字符。您还应该在STUFF函数的第三个参数中反映这一点。应该是2而不是1。否则,[NewQID]
列中的结果值将以空格开头。感谢您的回复。Qid正在聚合,但我在运行查询时看到重复的Employerid返回。例如,在我在问题中提供的第二个示例输出中,土豆公司返回三次,甜甜圈有限责任公司返回两次,菠萝物流公司返回四次等等。对于xml路径(“”)).value('text()','nvarchar(max)'),1,1…@BGonzaga。。完全使用您的示例数据。我没有看到重复的。