10
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

我收到这些错误

消息 156,级别 15,状态 1,第 7 行
关键字“SELECT”附近的语法不正确。
消息 156,级别 15,状态 1,第 8 行
关键字“in”附近的语法不正确。

如何使用枢轴对枢轴列下的字符串进行分组?

4

1 回答 1

20

When you are using the PIVOT function, you are required to use an aggregate function. The syntax of a PIVOT is:

From 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>;

With a string, you will need to use either the MIN() or MAX() aggregate function. The problem that you will run into is that these functions will return only one value for each column.

So in order to get the PIVOT to work, you will need to provide a distinct value that will keep the rows separate during the GROUP BY.

For your example, you can use 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

See SQL Fiddle with Demo.

The row_number() creates a distinct value that is assigned to each row in the job, when you apply the aggregate function and the GROUP BY in the PIVOT you will still get separate rows.

于 2013-03-11T11:25:07.350 回答