Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created January 11, 2010 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilversc/274651 to your computer and use it in GitHub Desktop.
Save chilversc/274651 to your computer and use it in GitHub Desktop.
create table Foo (data1 bit, data2 bit, data3 bit, seq int not null)
go
insert into Foo (data1, data2, data3, seq)
values (NULL, 0, 1, 1), (1, NULL, 0, 2), (0, 1, NULL, 3)
go
with unpivoted as (
select seq, value, col
from (select seq, data1, data2, data3 from Foo) a
unpivot (value FOR col IN (data1, data2, data3)) b
), firstSeq as (
select min(seq) as seq, col
from unpivoted
group by col
), data as (
select b.col, cast(b.value as tinyint) value
from firstSeq a
inner join unpivoted b on a.seq = b.seq and a.col = b.col
)
select * from data pivot (min(value) for col in (data1, data2, data3)) d
go
drop table Foo
go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment