简体   繁体   English

如何在T-SQL中将每隔一行转换为列?

[英]How to convert every other row to column in T-SQL?

Perhaps this was a question that has already been asked. 也许这是一个已被问过的问题。 How should one convert every other row to columns in T-SQL? 如何将每隔一行转换为T-SQL中的列? Here is some T-sql to create the table and sample data. 这里有一些T-sql来创建表和示例数据。

CREATE TABLE Names
(
     [ID] int, 
    HouseholdId int,
     [FullName] varchar(max), 
     [ssn] varchar(max),
    isPrimary bit
)
;

INSERT INTO names(ID, HouseholdId, [FullName], ssn, isPrimary)
VALUES
    (1, 10,'User1', '111111111', 1),
    (2, 10, 'User2', '222222222', 0),
    (3, 10, 'User3', '333333333', 0),
    (4, 10, 'User4', '444444444', 0),
    (5, 10,'User5', '555555555', 0),
    (6, 20, 'User6', '666666666', 1),
    (7, 20, 'User7', '777777777', 0)
;

I would like to convert every household's users into two columns, something like this. 我想将每个家庭的用户转换成两列,就像这样。

HouseHold   User Name 1 SSN 1       User Name 2 SSN 2
10          User1       111111111   User2       222222222
            User3       333333333   User4       444444444
            User5       555555555       
20          User6       666666666   User7       777777777

how would I do this? 我该怎么做?

here is the sql that will do what you are looking for. 这是sql将执行您正在寻找的。 It assigns a row number by partitioning within household id. 它通过在家庭ID内分区来分配行号。 Then uses a self join to lay out side-by-side. 然后使用自联接并排布局。 http://sqlfiddle.com/#!6/c8933/10/0 http://sqlfiddle.com/#!6/c8933/10/0

WITH T AS (
select HouseholdId, ID, Fullname, ssn
  , ROW_NUMBER() OVER(PARTITION BY HouseHoldId Order by ID) AS RNUM
FROM Names
)
SELECT A.HouseholdId, A.fullname as username1, A.SSN as ssn1
, B.fullname as username2, B.ssn as ssn2
FROM T A
LEFT JOIN T B ON A.householdID = B.HouseholdId
  AND (A.RNUM = B.RNUM - 1)
WHERE A.RNUM % 2 = 1 

This is how you could accomplish the same using a pivot . 这是使用pivot完成相同操作的方法。

select b.HouseholdID
, b.[User Name 1]
, b.[SSN 1]
, b.[User Name 2]
, b.[SSN 2]
from (
    select sub.HouseholdId
    , sub.col_nm_prelim + cast( (((sub.row_nbr + 1) % 2) + 1) as char(1)) as col_nm
    , ceiling(sub.row_nbr / 2.0) as row_nbr
    , sub.col_val
    from (
        select n.HouseholdId
        , 'User Name ' as col_nm_prelim
        , row_number() over (partition by n.HouseHoldID order by n.ID asc) as row_nbr
        , n.FullName as col_val
        from Names as n
        union all
        select n.HouseholdId
        , 'SSN ' as col_nm_prelim
        , row_number() over (partition by n.HouseHoldID order by n.ID asc) as row_nbr
        , n.SSN as col_val
        from Names as n
        ) as sub
    ) as a
pivot (max(a.col_val) for a.col_nm in ([User Name 1], [User Name 2], [SSN 1], [SSN 2])) as b
order by b.HouseholdID asc
, b.row_nbr asc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM