CREATE TABLE Foo (
keycol INT NOT NULL PRIMARY KEY,
col1 INT NOT NULL,
col2 INT NOT NULL,
col3 INT NOT NULL,
col4 INT NOT NULL);
INSERT INTO Foo VALUES(1, 5, 0, 1, 10);
INSERT INTO Foo VALUES(2, 0, 0, 3, 1);
INSERT INTO Foo VALUES(3, 0, 0, 0, 0);
INSERT INTO Foo VALUES(4, 9, 1, 22, 8);
INSERT INTO Foo VALUES(5, 8, 8, 8, 8);
-- max across columns with XQuery
SELECT c.query('keycol').value('.', 'INT') AS keycol,
c.value('local-name(./*[data(.)=
max(../*[not(local-name(.)="keycol") ])][1])',
'VARCHAR(20)') AS max_col,
c.value('max(*[not(local-name(.)="keycol")])', 'FLOAT') AS max_val
FROM (SELECT keycol, col1, col2, col3, col4
FROM Foo
FOR XML PATH, TYPE) AS T(x)
CROSS APPLY x.nodes('row') AS R(c);
keycol max_col max_val
------- -------- --------
1 col4 10
2 col3 3
3 col1 0
4 col3 22
5 col1 8
-- count non-zero columns with XQuery
SELECT c.query('keycol').value('.', 'INT') AS keycol,
c.value('count(*[not(local-name(.)="keycol")
and not(.=0)])',
'INT') AS cnt_non_zero
FROM (SELECT keycol, col1, col2, col3, col4
FROM Foo
FOR XML PATH, TYPE) AS T(x)
CROSS APPLY x.nodes('row') AS R(c);
keycol cnt_non_zero
------- ------------
1 3
2 2
3 0
4 4
5 4
-- max across columns with UNPIVOT
SELECT keycol, col AS max_col, val AS max_val
FROM (
SELECT keycol, val, col,
ROW_NUMBER() OVER(PARTITION BY keycol ORDER BY val DESC, col) AS rk
FROM Foo
UNPIVOT
(val FOR col IN (col1, col2, col3, col4)) AS U) AS T
WHERE rk = 1;
-- count non-zero columns with UNPIVOT
SELECT keycol, COUNT(NULLIF(val, 0)) AS cnt_non_zero
FROM Foo
UNPIVOT
(val FOR col IN (col1, col2, col3, col4)) AS U
GROUP BY keycol;
Labels: t-sql programming, unpivot, xml