透视在sql中

时间:2015-08-10 11:43:49

标签: sql sql-server sql-server-2008

我的sql表包含如下所示的数据

    emp id     empname  dept
    -------    ----     ------
  1              a        Hr
  2              b        Hr
  3              c        Tech
  4              d        Hr
  5              e        Admin
  7              f        Tech
  8              g        Admin

现在我想调整上面的表得到像这样的结果

                Hr    Tech    Admin
               -----  -----   -----
Empname        a       c       e
Empname        b       f       g
Empname        d

我只是想知道这是否可能在sql中使用pivoting或者还有其他任何意思来实现这个

2 个答案:

答案 0 :(得分:2)

您可以对ROW_NUMBER使用条件聚合:

SQL Fiddle

WITH Cte AS(
    SELECT *,
        RN = ROW_NUMBER() OVER(PARTITION BY dept ORDER BY empid)
    FROM tbl
)
SELECT
    [Hr] = MAX(CASE WHEN dept = 'Hr' THEN empname END),
    [Tech] = MAX(CASE WHEN dept = 'Tech' THEN empname END),
    [Admin] = MAX(CASE WHEN dept = 'Admin' THEN empname END)
FROM cte
GROUP BY rn

以下是PIVOT版本:

SQL Fiddle

;WITH Cte AS(
    SELECT *,
        RN = ROW_NUMBER() OVER(PARTITION BY dept ORDER BY empid)
    FROM tbl
)
SELECT *
FROM(
    SELECT
         dept, MAX(empname) AS empname,RN
    FROM Cte
    GROUP BY dept, RN
)t
PIVOT
(
    MAX(empname)
    FOR dept in ([Hr], [Tech], [Admin])
)piv

答案 1 :(得分:1)

这种类型的操作通常最好在表示层中完成。您似乎希望列中有三个不同的列表,因此这些行之间并不真正相关。

也就是说,您可以在SQL中执行此操作,但是您需要获得一个"列表位置"对于每一列。为此,请使用row_number()

select h.empname as hr, t.empname as tech, a.empname as admin
from (select empname, row_number() over (order by empname) as seqnum
      from table
      where dept = 'Hr'
     ) h full outer join
     (select empname, row_number() over (order by empname) as seqnum
      from table
      where dept = 'Tech'
     ) t
     on t.seqnum = h.seqnum full outer join
     (select empname, row_number() over (order by empname) as seqnum
      from table
      where dept = 'Admin'
     ) a
     on a.seqnum in (h.seqnum, t.seqnum)