T-sql中的问题

时间:2011-07-07 17:38:01

标签: sql sql-server sql-server-2005 tsql sql-server-2008

我有一个名为results的表,数据如下:

Response_ID  order    [part label]             [Answer text]     [Answer label]
124587       6        It was not clear         NULL               Yes
124587       6        Did not Understand      Null                Yes
124589       6        Other (Please specify):  Not enough         Yes 
124563       1        NULL                     Satisfied?         Yes
124583       11       Not frequent             NULL               Yes  
125687       2        NULL                     Resolved?          NO

我希望输出为:

Response_ID           [Part label]
124587                It was not clear,Did not Understand 
124589                Not enough         
124563                Yes
124583                Not frequent
125687                NO

逻辑是每当Order为6或11然后我需要显示[Part Label]如果[Part Label]有一个Response_ID的多个值,那么我需要连接它们但是当[Part Label]的值是其他(请注明):然后我需要使用Answer Text列中的值,如果订单不在6,11中,那么我需要显示Answer标签中的值

4 个答案:

答案 0 :(得分:3)

我没有看到关于订单的部分。我希望它现在有效。

DECLARE @t TABLE (Response_ID INT,[order] INT, [part label] VARCHAR(25), [Answer text] VARCHAR(15), [Answer label] VARCHAR(3))

INSERT @t VALUES (124587,6 , 'It was not clear'       , NULL        , 'Yes')
INSERT @t VALUES (124587,6 , 'Did not Understand'    , Null        , 'Yes' )
INSERT @t VALUES (124589,6 , 'Other (Please specify):','Not enough' , 'Yes')
INSERT @t VALUES (124563,1 , NULL                     ,'Satisfied?' , 'Yes')
INSERT @t VALUES (124583,11, 'Not frequent'           , NULL        , 'Yes') 
INSERT @t VALUES (125687,2 , NULL                     ,'Resolved?'  , 'NO' )

SET ARITHABORT ON

;WITH x AS   ( 
SELECT CASE WHEN [order] = 11 THEN 6 ELSE [order] END [order], response_id, COALESCE(CASE WHEN [part label] = 'Other (Please specify):' THEN [Answer text] ELSE [part label] end ,[Answer label]) [Part label] 
FROM @t
) 
SELECT response_id, STUFF(( 
        SELECT ',' + [Part label] 
        FROM x t1 
        WHERE t1.response_id = x.response_id and t1.[order] = x.[order]
        for xml path(''), type 
    ).value('.', 'varchar(max)'), 1, 1, '') [Part label] FROM x
GROUP BY response_id, [order]

结果:

response_id Part label
----------- -------------------------------------
124563      Yes
124583      Not frequent
124587      It was not clear,Did not Undersstand
124589      Not enough
125687      NO

答案 1 :(得分:1)

过去通过涉及ISNULL()的鲜为人知的角度来实现。这些天,人们用“FOR XML PATH”来做。请注意,这不受支持,但它现在适用于您。

Concatenating Row Values in T-SQL

答案 2 :(得分:0)

太糟糕了,没有简单的解决方案,因为Sql Server无法连接结果集行。看看这些问题:

Concatenate many rows into a single text string?

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

答案 3 :(得分:-1)

查看以下文章的“黑盒XML方法”部分。我相信它会满足你的需求。

https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/