2017-10-17 95 views
0

我意識到這是一個常見問題,但我想避免重複CASE語句多次。從Case Statement中刪除逗號

任何人都可以看到如何從字符串中排除「,」如果只有幾個案例是真實的(1)?

SELECT CONCAT 
(
    CASE WHEN Home = 1 THEN 'Own Home, ' END, 
    CASE WHEN Car = 1 THEN 'Car, ' END, 
    CASE WHEN Friend = 1 THEN 'Someone else''s home, ' END, 
    CASE WHEN Toilet = 1 THEN 'Toilet, ' END, 
    CASE WHEN Street = 1 THEN 'Street, park or beach, ' END, 
    CASE WHEN Squat = 1 THEN 'Squat, ' END, 
    CASE WHEN Other = 1 THEN 'Other' END 
) 
as 'Question 6', 
from table 

回答

1

試試這個

SELECT REVERSE(stuff(reverse(CONCAT 
(
    CASE WHEN Home = 1 THEN 'Own Home, ' END, 
    CASE WHEN Car = 1 THEN 'Car, ' END, 
    CASE WHEN Friend = 1 THEN 'Someone else''s home, ' END, 
    CASE WHEN Toilet = 1 THEN 'Toilet, ' END, 
    CASE WHEN Street = 1 THEN 'Street, park or beach, ' END, 
    CASE WHEN Squat = 1 THEN 'Squat, ' END, 
    CASE WHEN Other = 1 THEN 'Other' END 
)),1 ,1,'')) 
as 'Question 6', 
from TABLE 

或本

SELECT STUFF(CONCAT 
(
    CASE WHEN Home = 1 THEN ', Own Home' END, 
    CASE WHEN Car = 1 THEN ', Car' END, 
    CASE WHEN Friend = 1 THEN ', Someone else''s home' END, 
    CASE WHEN Toilet = 1 THEN ', Toilet' END, 
    CASE WHEN Street = 1 THEN ', Street, park or beach' END, 
    CASE WHEN Squat = 1 THEN ', Squat' END, 
    CASE WHEN Other = 1 THEN ', Other' END 
),1,2,'') 
as 'Question 6', 
from table 
+0

謝謝,但都不幸工作。 – Philip

+0

@詹姆斯你面臨的問題是什麼? –

+0

我試着用示例數據,它工作正常。你能提供你的樣本數據和預期的輸出。 –

0

它可能不是最快的,但只是爲了好玩。

WITH T3 AS 
(
    SELECT T1.PK, COALESCE(T2.Description, unpvt.Place) AS Description 
    FROM table AS T1 
    UNPIVOT 
     (Flag FOR Place IN (Home, Car, Friend, Toilet, Street, Squat, Other) 
    ) AS unpvt 
    LEFT OUTER JOIN 
    (
     SELECT * 
     FROM (VALUES('Home', 'Own Home'), ('Friend', 'Someone else''s home'), ('Street', 'Street, park or beach')) AS T(Place, Description) 
    ) AS T2 ON unpvt.Place = T2.Place 
    WHERE Flag = 1 
) 
SELECT PK, (STUFF((
       SELECT ', ' + Description 
       FROM T3 AS T4 
       WHERE T4.PK = T3.PK 
       FOR XML PATH('')), 1, 2, '')) AS Question6 
FROM T3 
GROUP BY PK 

要保留有問題的訂單,只需在上面的T2中添加一個訂單欄即可。

對於SQL Server 2017,它更簡單。

SELECT T1.PK, STRING_AGG(COALESCE(T2.Description, unpvt.Place), ', ') AS Description 
FROM table AS T1 
UNPIVOT 
    (Flag FOR Place IN (Home, Car, Friend, Toilet, Street, Squat, Other) 
) AS unpvt 
LEFT OUTER JOIN 
(
    SELECT * 
    FROM (VALUES('Home', 'Own Home'), ('Friend', 'Someone else''s home'), ('Street', 'Street, park or beach')) AS T(Place, Description) 
) AS T2 ON unpvt.Place = T2.Place 
WHERE Flag = 1 
GROUP BY PK