来自与客户相关的问题和响应的数据

时间:2019-05-07 15:16:29

标签: sql sql-server

我的表格中具有以下数据格式,客户回答测试问题,并将这些答复保存在表格中。问题分为几部分。我正在尝试获取与测试和某些部分相关的答案。

Sectiontable

      SecID    SecName
      1        Box
      2        square
      3        circle
CustomerTable     
     CID      CName
     92        John
     93        Andrew
     94        Chris
TestTable     
    testID      testkey    SecID
    18             T1        1
    19             T11       1
    21             T2        2 
    22             T21       2
    34             T3        3
    35             T4        3 

  CustomerTestresponse

    responseID      CID     testID     responseText
    1                92        18        T1Text
    2                92        19        T11Text
    3                92        34        T3Text
    4                92        35        T4Text
    5                92        22        T21Text
    6                93        19        Myresponse
    7                93        34        vendor
    8                93        21        cutomerout 

预期的查询输出:

CID    T1KeyResponse  T11KeyResponse   T3KeyResponse     T4KeyResponse
92      T1Text         T11Text           T3Text          T4Text
93                     Myresponse        vendor

1 个答案:

答案 0 :(得分:1)

这是四(4)步解决方案

-受到https://dba.stackexchange.com/questions/119844/how-to-pivot-without-fixed-columns-in-tsql

的高度敬仰

-(1)声明变量

DECLARE 
  @cols AS NVARCHAR(MAX)
  ,@query  AS NVARCHAR(MAX)
  ;

-(2)使用FOR XML PATH和STUFF连接新列标题的列表:
-请参阅SecID <> 2(您可能要更改此位置)

SELECT @cols = 
STUFF(
        (SELECT DISTINCT
             ',' + QUOTENAME(t.testkey + 'KeyResponse')
          FROM qandrResponse as r
          Left Join qandrTest as t
          On r.testID = t.testID  
          Where SecID <> 2      -- you may want to filter differently
          Order By ',' + QUOTENAME(t.testkey + 'KeyResponse')
                    FOR XML PATH(''), TYPE
         ).value('.', 'NVARCHAR(MAX)') 
                ,1,1,''
    );  
-- Select @cols;  -- uncomment to see the list, drag right side open to see full list

-(3)使用上面的@cols创建将要执行的完整sql字符串

set @query
    = N'SELECT CID,  ' + @cols + N' 
        From  (SELECT
                   r.CID
                  ,t.testkey + ''' + 'KeyResponse' + N''' as Keys
                  ,responseText
              FROM qandrResponse as r
              Left Join qandrTest as t
              On r.testID = t.testID
              ) x
  Pivot (
    max(responseText) for Keys IN (' + @cols + N')
  ) as p';
-- Select @query;  -- uncomment to see sql,  prettyprint with http://www.dpriver.com/pp/sqlformat.htm

-(4)执行查询

exec sp_executesql @query 

-结果

--CID   T11KeyResponse  T1KeyResponse   T3KeyResponse   T4KeyResponse
--92    T11Text         T1Text          T3Text          T4Text
--93    Myresponse      NULL            vendor          NULL