0

我为报告目的进行了查询,以列出尚未提交季度报告的雇主并列出尚未提交的季度。这是我的查询:

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 XMLstuff(). 我不确定如何stuff()在具有多个连接的查询上使用。任何帮助表示赞赏。

4

2 回答 2

1

这是for xml path子句做的伎俩。stuff只是去掉前导的','

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

db<>小提琴

退货

EmployerId  EmployerName    qids
1   Potato Inc  20193,20202,20203
2   Donuts LLC  20202,20203
3   Pineapple Logistics 20191,20192,20193,20194
于 2021-03-10T07:50:52.907 回答
0

试试这个解决方案

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
于 2021-03-10T07:24:32.590 回答