MS SQL Server子查询返回多个值(字符串)

时间:2014-12-04 07:52:17

标签: sql sql-server subquery

我在连接给出String结果的子查询的结果时出现问题。

实际上我的子查询有一个CASE WHEN语句,列表函数在MS SQL服务器中不起作用。所以我需要以某种方式连接这个子查询的结果,以便结果在一行中可见。

以下是我的代码:

select 
.......,(select CASE WHEN pm.PaymentType = 1 THEN   'Cash'      
                     WHEN pm.PaymentType = 2 THEN   'Check'       
                     WHEN pm.PaymentType = 3 THEN   'Credit Card'   
                     ELSE   'Money Order'   
                END
          from 
             <some tables with all the joins> 
          where 
             <all the conditions>) AS [PAYMENT TYPE],
....... 
from 
<some more tables with joins> 
where 
<some other conditions>

感谢您的帮助!!!

1 个答案:

答案 0 :(得分:0)

我知道的三种方式之一(也许最简单的方法)是xml-trick:

select 
.......,
     stuff(
          (
           select
               ',' + 
               CASE
                   WHEN pm.PaymentType = 1 THEN 'Cash'      
                   WHEN pm.PaymentType = 2 THEN 'Check'       
                   WHEN pm.PaymentType = 3 THEN 'Credit Card'   
                   ELSE 'Money Order'   
               END
           from <some tables with all the joins> 
           where <all the conditions>
           for xml path(''), type
        ).value('.', 'varchar(max)')
    ,1,1,'') AS [PAYMENT TYPE]
....... 
from 
<some more tables with joins> 
where 
<some other conditions>