
PUZZLE 53 COLLAPSING A TABLE BY COLUMNS 215
PUZZLE
53 COLLAPSING A TABLE BY COLUMNS
Robert Brown proposed this one in 2004. Suppose I have the following
table:
CREATE TABLE Foobar
(lvl INTEGER NOT NULL PRIMARY KEY,
color VARCHAR(10),
length INTEGER,
width INTEGER,
hgt INTEGER);
INSERT INTO Foobar
VALUES (1, 'RED', 8, 10, 12),
(2, NULL, NULL, NULL, 20),
(3, NULL, 9, 82, 25),
(4, 'BLUE', NULL, 67, NULL),
(5, 'GRAY', NULL, NULL, NULL);
I want to write a query that will return me a view collapsed from
“bottom-to-top” in order of level (lvl = 1 is the top, lvl = 5 is the bottom).
That means that the sample data would return:
(‘GRAY’, 9, 67, 25)
The principle ...