1

可能重复:
将多列拆分为多行

我的桌子看起来像这样

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

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

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

2 回答 2

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

于 2012-09-30T12:24:16.267 回答
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

这是一个现场演示

对于不支持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

现场演示

于 2012-09-30T11:53:32.323 回答