2013-03-11 63 views
7
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'附近的語法不正確。

如何使用透視將字符串分組在透視列下?

+0

@Downvoter關心評論?我的問題沒有什麼是錯的。 – 2013-05-07 13:44:51

+0

當然,這是一個有趣的問題。來自我的+1 ... – 2016-07-01 04:20:40

回答

17

當您使用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,當你應用聚合函數,並在PIVOT你仍然會得到不同的行的GROUP BY一個獨特的價值。