gbread
gbread

Reputation: 1

How can I return a list of row names and column names where the value is greater than 0 in SQL?

I've put together a reconciliation tool in SQL Server which identifies the number of record breaks by field (col 2 - col 4) between two identical (data types/structure) sources. The output returned is in the format below, grouped on col 1.

Col1  Col2  Col3  Col4
X     0     0     1
Y     0     1     1   
Z     1     0     1

I am trying to manipulate the output so that it provides a list of the Col 1 identifier and the name of any column names (col 2 - col 4) which have breaks (value > 0).

The expected output based on the above data would look like this.

Col1  FieldBreak
X     Col2
Y     Col3
Y     Col4
Z     Col2
Z     Col4

I'm newer to SQL (6 months of professional experience) and am stuck. Any help would be much appreciated!

Upvotes: 0

Views: 221

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269973

In any database, you can use:

select col1, 'col2' as col
from t
where col2 = 1
union all
select col1, 'col3' as col
from t
where col3 = 1
union all
select col1, 'col4' as col
from t
where col4 = 1;

There are probably more efficient methods, but those depend on the database. And for a small table efficiency may not be a concern.

In SQL Server, you would unpivot using apply:

select t.col1, v.*
from t cross apply
     (values ('col2', t.col2), ('col3', t.col3) . . . 
     ) v(col, val)
where v.val is not null;

If you have a lot of columns, you can construct the expression using a SQL statement (from INFORMATION_SCHEMA.COLUMNS) and/or using a spreadsheet.

Upvotes: 1

Related Questions