我已经看到了一些使用COALESCE和FOR XML尝试做的例子(似乎是更好的解决方案)。我只是无法正确理解语法。
这就是我所拥有的(我会将字段缩短到只有关键字段):
Table Fields
------ -------------------------------
Requisition ID, Number
IssuedPO ID, Number
Job ID, Number
Job_Activity ID, JobID (fkey)
RequisitionItems ID, RequisitionID(fkey), IssuedPOID(fkey), Job_ActivityID (fkey)
我需要一个查询,列出每行一个申请单及其关联的Jobs和IssuedPO。 (请购单编号以“R-”开头,作业编号以“J-”开头)。
示例:
R-123 | “PO1; PO2; PO3”| “J-12345; J-6780”
当然是亚当!
这是一个返回多行的查询。我必须使用外连接,因为并非所有申请都有分配给Jobs和/或IssuedPO的RequisitionItem(在这种情况下,他们的fkey ID当然只是null)。
SELECT DISTINCT Requisition.Number, IssuedPO.Number, Job.Number
FROM Requisition
INNER JOIN RequisitionItem on RequisitionItem.RequisitionID = Requisition.ID
LEFT OUTER JOIN Job_Activity on RequisitionItem.JobActivityID = Job_Activity.ID
LEFT OUTER JOIN Job on Job_Activity.JobID = Job.ID
LEFT OUTER JOIN IssuedPO on RequisitionItem.IssuedPOID = IssuedPO.ID
答案 0 :(得分:4)
以下是使用子查询执行此操作的一种方法:
select 'R-' + cast(r.number as varchar(32)) as RequisitionNumber
, (
select 'PO' + CAST(ip.number as varchar(32)) + ';'
from IssuedPO ip
join RequisitionItems ri
on ip.id = ri.IssuedPOID
where ri.RequisitionID = r.id
for xml path('')
) as POList
, (
select 'J-' + CAST(j.number as varchar(32)) + ';'
from Job j
join Job_Activity ja
on j.id = ja.JobID
join RequisitionItems ri
on ri.Job_ActivityID = ja.id
where ri.RequisitionID = r.id
for xml path('')
) as JobList
from Requisition r