2017-10-17 12 views
0

これはよくある質問ですが、CASEステートメントを複数回繰り返さないようにしたいと考えています。ケースステートメントからカンマを削除

少数のケースだけが真(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 

ORこの

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

@Jamesあなたが直面している問題は何ですか? –

+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 
関連する問題