向PIVOT添加新字段

时间:2016-03-04 16:15:10

标签: sql sql-server pivot

我拥有的是:

Person.where(:person_id => candidates, :online => true).count > 0

我的输出如下:

SELECT Value AS FieldName, [42] AS [KeyID_42],[600] AS [KeyID_600]
INTO ##Temp311037
FROM
(
  SELECT TransID, Value, FieldName
  FROM 
  (
     SELECT TransID, Convert(VarChar(250), [AccountNbr]) AS [AccountNbr], [CoAdd1]) AS [CoAdd1], Convert(VarChar(250), [CoAdd2]) AS [CoAdd2], Convert(VarChar(250), [CoCity]) AS [CoCity], Convert(VarChar(250), [CoFax]) AS [CoFax]
     FROM tblSQLContacts
  ) p
  UNPIVOT
  (
    FieldName FOR Value IN 
    ([accountNbr], [CoAdd1], [CoAdd2], [CoCity], [CoFax])
   )AS unpvt
) AS SourceTable
PIVOT
(
  MAX(FieldName)
  FOR TransID IN ([42],[600])
) AS PivotTable
WHERE [42] <> [600]

此数据来自表格FieldName KeyID_42 KeyID_600 AccountNbr 55664 55635 ChoiceFundYN 0 1 CoAdd1 PO Box 2200 1500 Mountain Drive CoAdd2 PO Box 7004 PO Box 4300 CoCity Las Vegas Birmingham CoFax 5552355622 5552975152 。好吧,问题是我将拥有大约20张桌子tblSQLContacts。因此,我希望能够在自己的字段中将表名添加到此输出中。所以最终的结果是:

UNION

这可能吗?我似乎无法使其发挥作用。理想情况下,我希望它成为第一个领域,但我会把它带到任何我能得到它的地方。

1 个答案:

答案 0 :(得分:1)

为了将表名添加到查询中,您需要将一个硬编码值添加到数据透视查询或子查询中。您可以对查询进行更改,如下所示:

SELECT Value AS FieldName, 
   [42] AS [KeyID_42],[600] AS [KeyID_600],
   TableName
INTO ##Temp311037
FROM
(
  -- add hard-coded value here
  SELECT TransID, Value, FieldName, 'tblSQLContacts' as TableName
  FROM 
  (
     SELECT TransID, Convert(VarChar(250), [AccountNbr]) AS [AccountNbr], 
        [CoAdd1]) AS [CoAdd1], 
        Convert(VarChar(250), [CoAdd2]) AS [CoAdd2], 
        Convert(VarChar(250), [CoCity]) AS [CoCity], 
        Convert(VarChar(250), [CoFax]) AS [CoFax]
      FROM tblSQLContacts
   ) p
  UNPIVOT
  (
     FieldName 
     FOR Value IN ([accountNbr], [CoAdd1], [CoAdd2], [CoCity], [CoFax])
  )AS unpvt
) AS SourceTable
PIVOT
(
  MAX(FieldName)
  FOR TransID IN ([42],[600])
) AS PivotTable
WHERE [42] <> [600]

由于每行的值都相同,因此不应改变枢轴的结果。