我的表格看起来像这样
accounting | research | sales | operations
------------------------------------------
3 | 5 | 6 | 0
必须接收具有两列和四行的结果集
dname | cnt
-----------------------
accounting | 3
research | 5
sales | 6
operations | 0
答案 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
对于不支持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
答案 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