6

我正在从这个遗留表转换数据:
Phones(ID int, PhoneNumber, IsCell bit, IsDeskPhone bit, IsPager bit, IsFax bit)

这些位域不能为空,并且可能所有四个位域都可以为 1。

我怎样才能取消旋转这个东西,以便我最终为每个位字段 = 1提供一个单独的行。例如,如果原始表看起来像这样......

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

...我希望结果如下:

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

谢谢!

4

2 回答 2

6

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

另请参见列到行 (UNPIVOT)

于 2010-01-21T22:15:21.537 回答
3

试试这个:

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
于 2010-01-21T22:22:17.273 回答