在pivot中选择列名称

时间:2013-12-11 16:50:27

标签: sql sql-server-2008

我需要在以下数据透视表中选择枢轴值来自的列的名称...

SELECT DISTINCT 
  filename,
  vals
FROM 
   (SELECT 
        filename,
        a1,
        a2,
        a3
   FROM 
      foo) p
UNPIVOT
   (vals FOR counts IN 
      (a1,a2,a3)
) AS bar

因此,如果一个值被选入vals列,但实际上来自a3,那么我需要将a3选入该记录中的另一列。所以......

   Vals   |   AColName
  235.53      a3
  48.54       a3
  93.49       a1

1 个答案:

答案 0 :(得分:1)

只需在select中使用count列,如下所示:

   SELECT DISTINCT 
  filename,
  vals,counts
FROM 
   (SELECT 
        filename,
        a1,
        a2,
        a3
   FROM 
      foo) p
UNPIVOT
   (vals FOR counts IN 
      (a1,a2,a3)
) AS bar