如何合并不同条件的CASE STATEMENT中的两列

时间:2017-08-23 04:02:25

标签: sql case sql-server-2014

我的预期结果应该是

----invoiceNo----
T17080003,INV14080011

但是现在,我已经提出了以下问题。

SELECT AccountDoc.jobCode,AccountDoc.shipmentSyskey,AccountDoc.docType,    
    CASE AccountDoc.docType
    WHEN 'M' THEN
    JobInvoice.invoiceNo
    WHEN 'I' THEN
    (STUFF((SELECT ', ' + RTRIM(CAST(AccountDoc.docNo AS VARCHAR(20)))
     FROM AccountDoc LEFT OUTER JOIN JobInvoice
     ON AccountDoc.principalCode = JobInvoice.principalCode AND 
     AccountDoc.jobCode = JobInvoice.jobCode
     WHERE (AccountDoc.isCancelledByCN = 0)
          AND (AccountDoc.docType = 'I')
          AND (AccountDoc.jobCode = @jobCode)
          AND (AccountDoc.shipmentSyskey = @shipmentSyskey)
          AND (AccountDoc.principalCode = @principalCode) FOR XML 
          PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,' '))
    END AS invoiceNo

FROM AccountDoc LEFT OUTER JOIN JobInvoice
ON JobInvoice.principalCode = AccountDoc.principalCode AND 
JobInvoice.jobCode = AccountDoc.jobCode
WHERE (AccountDoc.jobCode = @jobCode)
        AND (AccountDoc.isCancelledByCN = 0)
        AND (AccountDoc.shipmentSyskey = @shipmentSyskey)
        AND (AccountDoc.principalCode = @principalCode)

输出:

----invoiceNo----
T17080003
INV14080011

说明:

如果AccountDoc.docType = I,我想从表AccountDoc中选择docNo。 或者,如果AccountDoc.docType = M,请从表JobInvoice中选择invoiceNo。

问题是如果在同一个jobCode下有2个docType是M和I,我将如何显示这2张发票?

2 个答案:

答案 0 :(得分:0)

如果您有两行的情况,并且需要两列,则需要透视数据。你的sql有点乱,特别是你在另一个查询的select部分中将整个select语句放在一个case中的位。这两个查询几乎相同,您应该寻找更优化的编写方式。但是,您可以将整个sql包装在以下内容中:

select
    Jobcode, shipmentsyskey, [M],[I]
from(

  --YOUR ENTIRE SQL GOES HERE BETWEEN THESE BRACKETS. Do not alter anything else, just paste your entire sql here

) yoursql
pivot(
 max(invoiceno)
 for docType in([M],[I])
)pvt

答案 1 :(得分:0)

您可以使用CTE和FOR XML实现此目的。下面是我使用类似表格创建的示例代码 -

Create table #AccountDoc (
id  int ,
docType char(1),
docNo  varchar(10)
)

Create table #JobInvoice (
id  int ,
invoiceNo varchar(10)
)

insert into #AccountDoc
select 1 , 'M' ,'M1234'   
union all  select 2 , 'M' ,'M2345' 
union all  select 3 , 'M' ,'M3456' 
union all  select 4 , 'I' ,'I1234' 
union all  select 5 , 'I' ,'I2345' 
union all  select 6 , 'I' ,'I3456' 

insert into #JobInvoice
select 1 , 'INV1234'   
union all  select 2 , 'INV2345' 
union all  select 3 ,  'INV3456' 

select  * 
from #AccountDoc t1 left join #JobInvoice t2
on t1.id = t2.id  

with cte as
(
select isnull(  case  t1.docType  WHEN 'M' THEN t2.invoiceNo   WHEN 'I' then 
t1.docNo   end  ,'') invoiceNo
from #AccountDoc t1 left join #JobInvoice t2
on t1.id = t2.id  )
select invoiceNo + ',' from cte  For XML PATH ('')