对于案例场景,将SQL结果作为单行返回

时间:2017-03-27 11:23:50

标签: sql sql-server sql-server-2008

所以我有以下SQL查询:

SELECT CASE
WHEN STATUS = 0 THEN 'Pending' 
WHEN STATUS = 1 THEN 'Pending' 
WHEN STATUS = 2 THEN 'Confirmed' 
WHEN STATUS = 3 THEN 'Pending' 
WHEN STATUS = 4 THEN 'Pending' 
WHEN STATUS = 5 THEN 'Pending' 
WHEN STATUS = 6 THEN 'Paid' 
WHEN STATUS = 7 THEN 'Closed' 
WHEN STATUS = 8 THEN 'Rejected' END AS Statuses
FROM ORDERS 
WHERE opportunityid = 4054
GROUP BY Statuses

返回以下结果:

Pending
Confirmed

但是,我正在努力实现以下目标:

Pending,Confirmed

这可以在不使用@declare函数的情况下完成。

2 个答案:

答案 0 :(得分:2)

我想你想要这样的东西:

SELECT STUFF(MAX(CASE WHEN STATUS IN (0, 3, 4, 5) THEN ',Pending' ELSE '' END) +
             MAX(CASE WHEN STATUS IN (2) THEN ',Confirmed' ELSE '' END) +
             MAX(CASE WHEN STATUS IN (6) THEN ',Paid' ELSE '' END) +
             MAX(CASE WHEN STATUS IN (7) THEN ',Closed' ELSE '' END) +
             MAX(CASE WHEN STATUS IN (8) THEN ',Rejected' ELSE '' END),
             1, 1, ''
            ) as statuses
FROM ORDERS 
WHERE opportunityid = 4054;

答案 1 :(得分:0)

这将用于未预定义但存在于表中的状态:

DECLARE @t table(STATUSES INT,opportunityid INT)
INSERT @t values(1,4054),(2,4054),(3,4054)
INSERT @t values(1,4055),(6,4055),(7,4055),(12,4055)

DECLARE @t2 table(sta int, txt varchar(30))
INSERT @t2 
values
        (0, 'Pending'),
        (1, 'Pending'),
        (2, 'Confirmed'), 
        (3, 'Pending'),
        (4, 'Pending'),
        (5, 'Pending'),
        (6, 'Paid'),
        (7, 'Closed'), 
        (8, 'Rejected')

;WITH CTE as
(
  SELECT distinct opportunityid FROM @t
)
SELECT 
    t.*, 
    STUFF(( 
        SELECT distinct ',' + coalesce([txt], 'Unknown')
        FROM @t t1 
        LEFT JOIN
        @t2 x
        ON x.sta = t1.STATUSES
        WHERE t1.opportunityid = t.opportunityid
        for xml path(''), type 
    ).value('.', 'varchar(max)'), 1, 1, '') [status] 
FROM cte t