从案例陈述中删除逗号

时间:2017-10-17 03:19:52

标签: sql-server

我意识到这是一个常见的问题,但我想避免多次重复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

2 个答案:

答案 0 :(得分:1)

试试这个

 $.ajax(
            {
                url : formURL,//<<<-------- Here
                type: "POST",
                data : postData,
...

或者这个

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

答案 1 :(得分: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