CREATE TABLE pivot
(
legendary nvarchar(10),
dragon int,
psychic int,
fire int
);
插入记录
INSERT INTO pivot values
('false',20,43,47),
('true',12,14,15);
原始表格输出
SELECT * FROM pivot;
使用UNION运算符创建取消透视表。
CREATE TABLE unpivot AS
SELECT
legendary,
'dragon' AS type1,
dragon AS value
FROM
pivot
UNION
SELECT
legendary,
'psychic' AS type1,
psychic AS value
FROM
pivot
UNION
SELECT
legendary,
'fire' AS type1,
fire AS value
FROM
pivot
ORDER BY
type1;
查询反透视输出
SELECT
*
FROM
unpivot;
使用UNION和GROUP BY运算符反向透视。
CREATE TABLE pivot AS
SELECT
legendary,
MAX(dragon) AS dragon,
MAX(psychic) AS psychic,
MAX(fire) AS value
FROM
(
SELECT
legendary,
value AS dragon,
NULL AS psychic,
NULL AS fire
FROM
unpivot
WHERE
type1='dragon'
UNION
SELECT
legendary,
NULL AS dragon,
value AS psychic,
NULL AS fire
FROM
unpivot
WHERE
type1='psychic'
UNION
SELECT
legendary,
NULL AS dragon,
NULL AS psychic,
value AS fire
FROM
unpivot
WHERE
type1='fire'
)set_union
GROUP BY legendary;
1条答案
按热度按时间ajsxfq5m1#
如果很难理解
PIVOT
和UNPIVOT
运算符,只需使用UNION
和GROUP BY
来实现相同的操作。创建原始透视表
插入记录
原始表格输出
使用
UNION
运算符创建取消透视表。查询反透视输出
使用
UNION
和GROUP BY
运算符反向透视。查询透视输出
输出
希望这有帮助:)