如何为记录中找到的每个唯一值创建列

时间:2017-09-20 13:06:19

标签: sql-server

一个Web应用程序,允许用户创建自己的健康问卷表单,每个表单轮流允许用户自定义表单并添加问题和答案所需的任意数量的输入字段。 现在这些结果存储在两个表中

tblTransaction

  ID  Person      Date        FormName
 -------------------------------------------
  1   John Smith 19/09/2017   FamilyHistory
  2   Pat White  18/07/2017   FamilyHistory
  2   Pat White  18/07/2017   Diabetes

tblContent

  ID  TranID   FieldName               Value   
 --------------------------------------------
  1    1       Do you smoke            Yes
  2    1       How many a day          30
  3    2       Cancer in the family    No
  4    2       Blood pressure          No

我需要为Date,Person,FormName创建一个提取,然后将每个FormName找到的每个唯一FieldName列为一个单独的coloumn,同时考虑到FieldName的计数和值是未知的。

这就是结果应该是什么样的。

Date       Person      FormName         Do you smoke    How many a day      
----------------------------------------------------------------------
19/09/2017 John Smith  FamilyHistory    Y               30    

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT 
  t.Date AS Date,
  t.[Person],
  t.[FormName],
  MAX(CASE WHEN c.FieldName = 'Do you smoke' THEN c.Value END) AS 'Do you smoke',
  MAX(CASE WHEN c.FieldName = 'How many a day' THEN c.Value END) AS 'How many a day',
  MAX(CASE WHEN c.FieldName = 'Cancer in the family' THEN c.Value END) AS 'Cancer in the family',
  MAX(CASE WHEN c.FieldName = 'Blood pressure' THEN c.Value END) AS 'Blood pressure'
FROM tblContent AS c
INNER JOIN tblTransaction AS t ON c.[TranID] = t.[Id]
WHERE t.Person = 'John Smith' AND t.FormName = 'FamilyHistory'
GROUP BY  t.Date,
  t.[Person],
  t.[FormName];

demo

您还可以使用pivot

SELECT *
FROM
(
    SELECT t.Date,
      t.[Person],
      t.[FormName],
      c.FieldName,
      c.Value
    FROM tblContent AS c
    INNER JOIN tblTransaction AS t ON c.[TranID] = t.[Id]
    WHERE t.Person = 'John Smith' AND t.FormName = 'FamilyHistory'
) AS c
PIVOT
(
   MAX(Value)
   FOR FieldName IN([Do you Smoke], [How many a Day])
) AS p;

pivot demo