枢轴列下的数据透视表字符串分组?

时间:2013-03-11 11:15:54

标签: sql sql-server sql-server-2008 pivot pivot-table

JOB        ENAME
--------  ----------
ANALYST    SCOTT
ANALYST    FORD
CLERK      SMITH
CLERK      ADAMS
CLERK      MILLER
CLERK      JAMES
MANAGER    JONES
MANAGER    CLARK
MANAGER    BLAKE
PRESIDENT  KING
SALESMAN   ALLEN
SALESMAN   MARTIN
SALESMAN   TURNER
SALESMAN   WARD

我想格式化结果集,以便每个作业都有自己的列:

CLERKS  ANALYSTS  MGRS   PREZ  SALES
------  --------  -----  ----  ------
MILLER  FORD      CLARK  KING  TURNER
JAMES   SCOTT     BLAKE        MARTIN
ADAMS             JONES        WARD
SMITH 

我试过

SELECT ANALYST, CLERK, MANAGER, PRESIDENT, SALESMAN from
(
  SELECT ename, job from emp
) as st
pivot
(
  SELECT ename
  FOR job in (ANALYST, CLERK, MANAGER, PRESIDENT, SALESMAN)
) as pivottable

我收到了这些错误

  

Msg 156,Level 15,State 1,Line 7
  关键字'SELECT'附近的语法不正确。
  Msg 156,Level 15,State 1,Line 8
  关键字'in'附近的语法不正确。

如何使用数据透视表在数据透视列下对字符串进行分组?

1 个答案:

答案 0 :(得分:18)

使用PIVOT函数时,需要使用聚合函数。 PIVOT的语法是:

来自MSDN

SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the source query>
PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;

使用字符串,您需要使用MIN()MAX()聚合函数。您将遇到的问题是这些函数将为每列返回一个值。

因此,为了让PIVOT生效,您需要提供一个明确的值,以便在GROUP BY期间保持行分开。

对于您的示例,您可以使用row_number()

SELECT ANALYST, CLERK, MANAGER, PRESIDENT, SALESMAN 
from
(
  SELECT ename, job,
    row_number() over(partition by job order by ename) rn
  from emp
) as st
pivot
(
  max(ename)
  FOR job in (ANALYST, CLERK, MANAGER, PRESIDENT, SALESMAN)
) as pivottable

请参阅SQL Fiddle with Demo

row_number()创建了一个分配给job中每一行的不同值,当您应用聚合函数时,GROUP BY中的PIVOT仍将保留获得单独的行。