使用交叉申请

时间:2017-02-02 01:54:37

标签: sql sql-server

我要求按照以下代码生成客户详细信息报告。我的附加要求是,如果我的电子邮件ID包含多于1个值,则通过创建新记录来生成报告。它应该是这样的,

C000279   Cust1      xx@yy.com
C000279   Cust1      yy@xx.com

我的代码是这样的,

select distinct c.PKEY [Customer Code],
c.NAME [Customer Name],
mi.MODEL [Machine #],
(select Split.a.value('.','varchar(100)') email
from 
    (select       
        cast('<x>' + replace(m.CONTACT_EMAIL,';','</x><x>')+'</x>' as XML) as x
    from tblMachineContact m
    where mi.PKEY=m.MAC_PKEY and m.CONTACT_CATEGORY_PKEY in ('PC'))t
cross apply x.nodes ('/x') as Split(a)) [Customer Email]
from tblMachine mi
inner join tblCustomers on m.CUST_PKEY=c.PKEY
where mi.STATUS='A'

由于我的电子邮件ID具有多个值,我想将其拆分为另一行。但是由于这个原因,我的子查询返回了超过1行并导致错误。有任何解决方案可以达到这个目的吗?

@Gordon, 我正在使用另一个条件。但是这个来自外部的电子邮件ID适用于category = PC适用于我的所有类别。我只希望它适用于我的PC类别的记录。我怎样才能实现?

以下是我的查询,

select distinct c.PKEY [Customer Code],
c.NAME [Customer Name],
mi.MODEL [Machine #],
(select Split.a.value('.','varchar(100)') email
from 
    (select       
        cast('<x>' + replace(m.CONTACT_EMAIL,';','</x><x>')+'</x>' as XML) as x
    from tblMachineContact m
    where mi.PKEY=m.MAC_PKEY and m.CONTACT_CATEGORY_PKEY in ('PC'))t
cross apply x.nodes ('/x') as Split(a)) [Customer Email]
from tblMachine mi
inner join tblCustomers on m.CUST_PKEY=c.PKEY
where mi.STATUS='A' and m.CONTACT_CATEGORY_PKEY in ('PC','TC','ER')

1 个答案:

答案 0 :(得分:1)

我没有遵循代码的所有细微差别,但如果您使用outer apply而不是相关的子查询,这应该有效:

select distinct c.PKEY [Customer Code], c.NAME [Customer Name],
       mi.MODEL [Machine #],
       x.[Customer Email]
from tblMachine mi inner join
     tblCustomers c
     on m.CUST_PKEY = c.PKEY outer apply
     (select Split.a.value('.','varchar(100)') as [Customer Email]
      from (select cast('<x>' + replace(m.CONTACT_EMAIL,';','</x><x>')+'</x>' as XML) as x
            from tblMachineContact m
            where mi.PKEY = m.MAC_PKEY and m.CONTACT_CATEGORY_PKEY in ('PC')
           ) t cross apply
           x.nodes('/x') as Split(a)
     ) x
where mi.STATUS = 'A';