反向部署

时间:2012-09-30 11:48:33

标签: sql sql-server unpivot

  

可能重复:
  Split Multiple Columns into Multiple Rows

我的表格看起来像这样

accounting | research | sales | operations 
------------------------------------------
         3 |        5 |     6 |          0

必须接收具有两列和四行的结果集

dname      |        cnt
-----------------------
accounting |          3
research   |          5
sales      |          6
operations |          0

2 个答案:

答案 0 :(得分:1)

使用UNPIVOT表格运算符,如下所示:

DECLARE @t table (accounting int, research int, sales int, operations int);

INSERT INTO @t VALUES(3, 5, 6, 0);

   SELECT dname, cnt
    FROM
    (
       SELECT accounting, research, sales, operations 
       FROM @t
    ) t 
    UNPIVOT
    (
      cnt FOR dname IN (accounting, research, sales, operations )
    ) u

这是live demo

对于不支持UNPIVOT表运算符的RDBMS,这是执行此操作的标准sql查询:

SELECT dname,
  CASE dname
    WHEN 'accounting' THEN accounting 
    WHEN 'research'   THEN research
    WHEN 'sales'      THEN sales
    WHEN 'operations' THEN operations
  END AS cnt
FROM @t
CROSS JOIN
(
   SELECT 'accounting' dname
   UNION ALL SELECT 'research' 
   UNION ALL SELECT 'sales' 
   UNION ALL SELECT 'operations'
) t2
WHERE dname IS NOT NULL

Live DEMO

答案 1 :(得分:1)

并非所有RDBMS都具有UNPIVOT功能,因此如果您没有UNPIVOT运算符,则执行此操作的另一种方法是使用UNION ALL

select 'accounting' dname, IsNull(accounting, 0) cnt
from yourtable
union all
select 'research' dname, IsNull(research, 0) cnt
from yourtable
union all
select 'sales' dname, IsNull(sales, 0) cnt
from yourtable
union all
select 'operations' dname, IsNull(operations, 0) cnt
from yourtable

请参阅SQL Fiddle With Demo