Pergunta

Estou transformando dados desta tabela herdada:
Phones(ID int, PhoneNumber, IsCell bit, IsDeskPhone bit, IsPager bit, IsFax bit)

Esses campos de bits não são nulos e, potencialmente, todos os campos de quatro bits podem ser 1.

Como posso descrever essa coisa para acabar com uma linha separada para cada campo de bits = 1. Por exemplo, se a tabela original se parece com isso ...

ID, PhoneNumber, IsCell, IsPager, IsDeskPhone, IsFax
----------------------------------------------------
1   123-4567     1       1        0            0
2   123-6567     0       0        1            0
3   123-7567     0       0        0            1
4   123-8567     0       0        1            0

... Eu quero que o resultado seja o seguinte:

ID   PhoneNumber   Type
-----------------------
1    123-4567      Cell
1    123-4567      Pager
2    123-6567      Desk
3    123-7567      Fax
4    123-8567      Desk

Obrigado!

Foi útil?

Solução

Versão 2005/2008

SELECT ID, PhoneNumber, Type
FROM
(SELECT ID, PhoneNumber,IsCell, IsPager, IsDeskPhone, IsFax
 FROM Phones) t
UNPIVOT
( quantity FOR Type  IN
    (IsCell, IsPager, IsDeskPhone, IsFax)
) AS u
where quantity = 1

Veja também Coluna para Row (Unpivot)

Outras dicas

Experimente isso:

DROP TABLE #Phones
CREATE TABLE #Phones
(
    Id int,
    PhoneNumber varchar(50),
    IsCell bit,
    IsPager bit,
    IsDeskPhone bit,
    IsFax bit
)

INSERT INTO #Phones VALUES (1, '123-4567', 1, 1, 0, 0)
INSERT INTO #Phones VALUES (2, '123-6567', 0, 0, 1, 0)
INSERT INTO #Phones VALUES (3, '123-7567', 0, 0, 0, 1)
INSERT INTO #Phones VALUES (4, '123-8567', 0, 0, 1, 0)

SELECT Id, PhoneNumber, [Type]
FROM (
    SELECT  Id, PhoneNumber, 
            Cell = IsCell, Pager = IsPager, 
            Desk = IsDeskPhone, Fax = IsFax
    FROM #Phones
) a 
UNPIVOT(
    something FOR [Type] IN (Cell, Pager, Desk, Fax )
) as upvt
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top