如何使用格式在一个值中获取列值

时间:2014-01-03 20:04:56

标签: sql-server

我想选择要添加的所有已确认状态值,因为逗号分隔和未确认状态值应添加到使用sql查询分隔'/'的相同值。

我尝试使用'FOR XML PATH'但是遇到了条件。我想使用单个'FOR XML PATH('')'来获得结果。不知道这是否可能。

我的表结构是这样的

的Sample1

ID  State           IsConfirmed
1   Karnataka       1
2   Rajasthan       1
3   Tamilnadu       1
4   Maharashtra     0
5   Gujrat          1
6   Kerala          0
7   Punjab          1
8   Hariyana        0

样品2

ID  State           IsConfirmed
1   Karnataka       0
2   Rajasthan       0
3   Tamilnadu       0
4   Maharashtra     0

预期结果低于

对于Sample1

Karnataka,Rajasthan,Tamilnadu,Gujrat,Punjab,Maharashtra/Kerala/Hariyana

对于Sample2

Karnataka/Rajasthan/Tamilnadu/Maharashtra

2 个答案:

答案 0 :(得分:1)

DECLARE @Confirmed VARCHAR(max), @NotConfirmed VARCHAR(MAX)

SELECT @Confirmed = COALESCE(@Confirmed + ',', '') + State
FROM YourTableName
WHERE IsConfirmed = 1

SELECT @NotConfirmed = COALESCE(@NotConfirmed + '/', '') + State
FROM YourTableName
WHERE IsConfirmed = 0

SELECT COALESCE(@Confirmed, '') + COALESCE(',' + @NotConfirmed, '')

答案 1 :(得分:1)

我可能希望将已确认和未确认的列视为单独的列,因此我以这种方式编写了答案,然后将它们合并为最终结果。这样就可以按照您的要求给出答案,并通过简单的方法将其更改为我喜欢的方式。

CREATE TABLE #Sample1 
(
    ID Int 
    , State VarChar(25)
    , IsConfirmed Bit 
)

INSERT INTO #Sample1
SELECT 1, 'Karnataka', 1
UNION SELECT 2, 'Rajasthan', 1
UNION SELECT 3, 'Tamilnadu', 1
UNION SELECT 4, 'Maharashtra', 0
UNION SELECT 5, 'Gujrat', 1
UNION SELECT 6, 'Kerala', 0
UNION SELECT 7, 'Punjab', 1
UNION SELECT 8, 'Hariyana', 0

SELECT ConfirmedList + ISNULL(',' + UnconfirmedList, '')
FROM (
SELECT ConfirmedList = substring((SELECT (', ' + S.State)
                            FROM #Sample1 S 
                            WHERE S.IsConfirmed = 1
                            ORDER BY S.ID 
                            FOR XML PATH ('')
                            ), 3, 8000)
    , UnconfirmedList = substring((SELECT ('/' + S.State)
                            FROM #Sample1 S 
                            WHERE S.IsConfirmed = 0
                            ORDER BY S.ID 
                            FOR XML PATH ('')
                            ), 2, 8000)
)x

DROP TABLE #Sample1