如何将记录数据转换为列

时间:2013-06-26 07:31:26

标签: sql sql-server sql-server-2008 pivot

请查找示例数据:

h_company_id    company_nm      mainphone1      phone_cnt
20816          800 Flowers      5162377000         3
20816          800 Flowers      5162377131         1
20820         1st Source Corp.  5742353000         3
20821       1st United Bancorp  5613633400         2
20824         3D Systems Inc.   8033273900         4
20824         3D Systems Inc.   8033464010         1
11043         3I Group PLC      2079757115         1
11043         3I Group PLC      2079753731         15

期望的输出:

h_company_id    company_nm          mainphone1    phone_cnt  mainphone2    phone_cnt2
20816        800 Flowers    5162377000  3        5162377131        1
20820        1st Source Corp.   5742353000  3           NULL          NULL
20821        1st United Bancorp 5613633400  2           NULL          NULL
20824        3D Systems Inc.    8033273900  4        8033464010        1
11043        3I Group PLC   2079757115  1        2079753731        15

(在记事本/ excel上面复制)

嗨,大家好,

我想将列mainphone1和phone_cnt的记录转换为新列mainphone2phone_cnt2,以便列h_company_id中的数据应该是唯一的意味着应该有只有h_company_id的单个条目。

提前致谢!

3 个答案:

答案 0 :(得分:3)

从行转换为列称为PIVOT,有几种不同的方法可以在SQL Server中完成。

聚合/ CASE:您可以将聚合函数与CASE表达式一起使用。这可以通过将row_number()窗口函数应用于表中的数据来实现:

select h_company_id, company_nm,
  max(case when seq = 1 then mainphone1 end) mainphone1,
  max(case when seq = 1 then phone_cnt end) phone_cnt1,
  max(case when seq = 2 then mainphone1 end) mainphone2,
  max(case when seq = 2 then phone_cnt end) phone_cnt2
from
(
  select h_company_id, company_nm, mainphone1, phone_cnt,
    row_number() over(partition by h_company_id order by mainphone1) seq
  from yourtable
) d
group by h_company_id, company_nm;

SQL Fiddle with Demo。 CASE表达式检查序列号是否具有值1或2,然后将数据放在列中。

UNPIVOT / PIVOT:由于您希望PIVOT存在于两列中的数据,因此您需要首先取消mainphone1phone_cnt列的UNPIVOT以使它们进入同一列,然后应用PIVOT功能。

UNPIVOT代码将类似于以下内容:

select h_company_id, company_nm,
  col+cast(seq as varchar(10)) col,
  value
from 
(
  select h_company_id, company_nm, 
    cast(mainphone1 as varchar(15)) mainphone,
    cast(phone_cnt as varchar(15)) phone_cnt,
    row_number() over(partition by h_company_id order by mainphone1) seq
  from yourtable
) d
unpivot
(
  value
  for col in (mainphone, phone_cnt)
) unpiv;

Demo。此查询以下列格式获取数据:

| H_COMPANY_ID |         COMPANY_NM |        COL |      VALUE |
---------------------------------------------------------------
|        11043 |       3I Group PLC | mainphone1 | 2079753731 |
|        11043 |       3I Group PLC | phone_cnt1 |         15 |
|        11043 |       3I Group PLC | mainphone2 | 2079757115 |
|        11043 |       3I Group PLC | phone_cnt2 |          1 |
|        20816 |        800 Flowers | mainphone1 | 5162377000 |

然后将PIVOT函数应用于col

中的值
select h_company_id, company_nm, 
  mainphone1, phone_cnt1, mainphone2, phone_cnt2
from 
(
  select h_company_id, company_nm,
    col+cast(seq as varchar(10)) col,
    value
  from 
  (
    select h_company_id, company_nm, 
      cast(mainphone1 as varchar(15)) mainphone,
      cast(phone_cnt as varchar(15)) phone_cnt,
      row_number() over(partition by h_company_id order by mainphone1) seq
    from yourtable
  ) d
  unpivot
  (
    value
    for col in (mainphone, phone_cnt)
  ) unpiv
) src
pivot
(
  max(value)
  for col in (mainphone1, phone_cnt1, mainphone2, phone_cnt2)
) piv;

请参阅SQL Fiddle with Demo

多个联接:您也可以多次加入您的桌面以获得结果。

;with cte as
(
  select h_company_id, company_nm, mainphone1, phone_cnt,
    row_number() over(partition by h_company_id order by mainphone1) seq
  from yourtable
)
select c1.h_company_id,
  c1.company_nm,
  c1.mainphone1,
  c1.phone_cnt phone_cnt1,
  c2.mainphone1 mainphone2,
  c2.phone_cnt phone_cnt2
from cte c1
left join cte c2
  on c1.h_company_id = c2.h_company_id
  and c2.seq = 2
where c1.seq = 1;

请参阅SQL Fiddle with Demo

动态SQL:最后,如果您想要转换未知数量的值,则需要实现动态SQL以获得结果:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(col+cast(seq as varchar(10))) 
                    from
                    (
                      select row_number() over(partition by h_company_id order by mainphone1) seq
                      from yourtable
                    ) d
                    cross apply
                    (
                      select 'mainphone', 1 union all
                      select 'phone_cnt', 2
                    ) c (col, so)
                    group by seq, so, col
                    order by seq, so
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT h_company_id, company_nm,' + @cols + ' 
              from 
             (
                select h_company_id, company_nm,
                  col+cast(seq as varchar(10)) col,
                  value
                from 
                (
                  select h_company_id, company_nm, 
                    cast(mainphone1 as varchar(15)) mainphone,
                    cast(phone_cnt as varchar(15)) phone_cnt,
                    row_number() over(partition by h_company_id order by mainphone1) seq
                  from yourtable
                ) d
                unpivot
                (
                  value
                  for col in (mainphone, phone_cnt)
                ) unpiv
            ) x
            pivot 
            (
                max(value)
                for col in (' + @cols + ')
            ) p '

execute(@query)

SQL Fiddle with Demo。所有结果都是:

| H_COMPANY_ID |         COMPANY_NM | MAINPHONE1 | PHONE_CNT1 | MAINPHONE2 | PHONE_CNT2 |
-----------------------------------------------------------------------------------------
|        20820 |   1st Source Corp. | 5742353000 |          3 |     (null) |     (null) |
|        20821 | 1st United Bancorp | 5613633400 |          2 |     (null) |     (null) |
|        20824 |    3D Systems Inc. | 8033273900 |          4 | 8033464010 |          1 |
|        11043 |       3I Group PLC | 2079753731 |         15 | 2079757115 |          1 |
|        20816 |        800 Flowers | 5162377000 |          3 | 5162377131 |          1 |

答案 1 :(得分:0)

以下内容可行(假设您的表名为company):

SELECT
    c1.h_company_id,
    c1.company_nm,
    c1.mainphone1,
    c1.phone_cnt,
    c2.mainphone1 AS mainphone2,
    c2.phone_cnt AS phone_cnt2
FROM
    company AS c1
LEFT JOIN
    company AS c2 ON c2.h_company_id = c1.h_company_id

但是,为了尊重良好做法,将数据分成两个表是不是更好?

  • company表,包含2列:h_company_id(PK)和company_nm
  • phone表格,包含4列:phone_id(PK),h_company_id(FK),mainphonephone_cnt

它允许您为每个公司提供任意数量的电话号码(包括没有)。

答案 2 :(得分:0)

尝试此查询。这将有助于你

SELECT t.H_COMPANY_ID,t.COMPANY_NM, a.mainphone1,a.PHONE_CNT,b.mainphone1 mainphone2,b.PHONE_CNT PHONE_CNT2 FROM table_name t
INNER JOIN
(
   SELECT h_company_id,phone_cnt,mainphone1 FROM table_name
   WHERE mainphone1 
   IN(
       SELECT max(mainphone1) mainphone1 FROM table_name GROUP BY h_company_id
     )
)a ON t.H_COMPANY_ID = a.h_company_id
INNER JOIN
(
   SELECT h_company_id,phone_cnt,mainphone1 FROM table_name
   WHERE mainphone1 
   IN(
       SELECT min(mainphone1) mainphone1 from table_name GROUP BY h_company_id
     )
)b ON t.H_COMPANY_ID = b.H_COMPANY_ID 
GROUP BY t.H_COMPANY_ID,a.mainphone1,t.COMPANY_NM,a.PHONE_CNT,b.mainphone1,b.PHONE_CNT