SQL查询:将值重新编码为新变量

时间:2017-07-18 14:34:24

标签: sql-server

我使用的数据库包含客户问卷的答案。我的问题是,虽然每个客户都被问了几个问题,但数量和具体问题各不相同,每个问题都有自己的记录。所以每份调查问卷都有三个问题。

我对问题类型进行了分组,并希望每个调查问卷都有一条记录,并附有所有答案。

如果qnumber [1,2,3],[4,5,6],[7,8,9]相同且信息是这样的

ID,qnumber,avalue  
1,1,4  
1,4,5  
1,7,6  
2,2,5  
2,5,6  
2,8,7  
3,3,7  
3,6,8  
3,9,9  

我想构建查询,以便获得如下结果:

ID,q1,q2,q3  
1,4,5,6  
2,5,6,7  
3,6,7,8  

这甚至可能吗?

2 个答案:

答案 0 :(得分:0)

试试这个

;With cte(ID,qnumber,avalue  )
AS
(
SELECT 1,1,4  UNION ALL
SELECT 1,4,5  UNION ALL
SELECT 1,7,6  UNION ALL
SELECT 2,2,5  UNION ALL
SELECT 2,5,6  UNION ALL
SELECT 2,8,7  UNION ALL
SELECT 3,3,7  UNION ALL
SELECT 3,6,8  UNION ALL
SELECT 3,9,9  
)
SELECT Cstring AS CombinedValue
    ,SUBSTRING(Cstring, 0, CHARINDEX(',', Cstring)) AS ID
    ,SUBSTRING(Cstring, CHARINDEX(',', Cstring) + 1, CHARINDEX(',', Cstring) - 1) AS Q1
    ,SUBSTRING(Cstring, CHARINDEX(',', Cstring) + 5, CHARINDEX(',', Cstring) - 1) AS Q2
    ,SUBSTRING(Cstring, CHARINDEX(',', Cstring) + 9, CHARINDEX(',', Cstring) - 1) AS Q2
FROM (
    SELECT DISTINCT STUFF((
                SELECT ',' + CAST(qnumber AS VARCHAR) + ',' + CAST(avalue AS VARCHAR)
                FROM cte i
                WHERE i.ID = o.ID
                FOR XML PATH('')
                ), 1, 1, '') AS Cstring
    FROM cte o
    ) DT

结果

  CombinedValue    ID   Q1  Q2  Q2
    ------------------------------
    1,4,4,5,7,6     1   4   5   6
    2,5,5,6,8,7     2   5   6   7
    3,7,6,8,9,9     3   7   8   9

答案 1 :(得分:0)

CREATE TABLE #Temp
(
    ID  INT,
    qnumber INT,
    avalue  INT
)

INSERT #Temp
VALUES 
(1,1,4),
(1,4,5),
(1,7,6),
(2,2,5),
(2,5,6),
(2,8,7),
(3,3,7),
(3,6,8),
(3,9,9)


SELECT ID, [1] AS q1, [2] AS q2, [3] AS q3
FROM (
    SELECT ID, [1], [2], [3]
    FROM (
        SELECT ID, 
            CASE WHEN qnumber IN (1, 2, 3) THEN 1
                 WHEN qnumber IN (4, 5, 6) THEN 2
                 WHEN qnumber IN (7, 8, 9) THEN 3
            END AS qnumber,
            avalue
        FROM #Temp) AS SourceTable
    PIVOT
    (AVG(avalue)
    FOR qnumber IN ([1], [2], [3])) AS PivotTable
) t

DROP TABLE #Temp