开发者

TSQL - Help with UNPIVOT

I am transforming data from this legacy table:

Phones(ID int, PhoneNumber, IsCell bit, IsDeskPhone bit, IsPager bit, IsFax bit)

These bit fields are not nullables and, potentially, all four bit fields can be 1.

How can I unpivot this thing so that I end up with a separate row for each bit field = 1. For instance, if the original table looks like this...

ID, PhoneNumber, I开发者_开发百科sCell, 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

... I want the result to be the following:

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

Thanks!


2005/2008 version

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

see also Column To Row (UNPIVOT)


Try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜