我试图动态地将行转置为列。在下一页(http://forums.teradata.com/forum/analytics/transpose-rows-to-columns-with-1-n-columns)中,我发现了一个脚本(来自Kirubhakaran),它做了一些非常接近的事情。
我试图按如下方式获取多个帐户的月末值(下面的代码):
AccountNr,Balance201504,Balance201505,Balance201506
123 1000 1200 900
456 2000 1900
我有以下问题,希望你能帮助我:
非常感谢您的帮助。
CREATE TABLE EoMBalance
(
AccountNr int,
Mnth varchar(6),
Balance int
);
INSERT INTO EoMBalance
(AccountNr, Mnth, Balance)
VALUES
(123, '201504', 1000),
(123, '201505', 1200),
(123, '201506', 900),
(456, '201504', 2000),
(456, '201505', 1900);
-- Passive construction of Balance per end of month in columns.-----
SELECT
AccountNr,
MAX(CASE WHEN Mnth = '201504' THEN Balance ELSE NULL END) AS Balance201504,
MAX(CASE WHEN Mnth = '201505' THEN Balance ELSE NULL END) AS Balance201505,
MAX(CASE WHEN Mnth = '201506' THEN Balance ELSE NULL END) AS Balance201506
FROM
EoMBalance
GROUP BY
AccountNr
ORDER BY
AccountNr