Domanda

Sto trasformazione dei dati da questa tabella legacy:
Phones(ID int, PhoneNumber, IsCell bit, IsDeskPhone bit, IsPager bit, IsFax bit)

Questi campi di bit non sono nullables e, potenzialmente, tutti e quattro i campi di bit può essere 1.

Come posso UNPIVOT questa cosa in modo che io alla fine con una riga separata per ogni campo di bit = 1 . Per esempio, se la tabella originale si presenta così ...

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

... Voglio che il risultato sia il seguente:

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

Grazie!

È stato utile?

Soluzione

2005/2008 versione

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

puoi anche consultare Colonna a remare (UNPIVOT)

Altri suggerimenti

Prova questo:

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top