2

我试图打破和合并这样的表格的结果。(对于宾果游戏!)我可以很容易地编写 CASE 以按第一个字母将列分开。但是,我最终会显示空值,因为行被它们的 ID 视为不同。我在这里尝试了一些合并示例,但似乎被难住了。ID 无关紧要,我可以控制如何收集初始数据。

ID  |  Number     |
====================
1   |      N6     | 
2   |      B22    |
3   |      B5     |
4   |      I9     |
5   |      N4     |


B  |  I  |  N  |  G  |  O  |
============================
B5 |  I9 | N4  |  -- | --  |
B22| --  | N6  |  -- | --  |
4

2 回答 2

3
;WITH CTE AS
(
SELECT *,
       LEFT([Number],1) AS Letter,
       ROW_NUMBER() OVER (PARTITION BY LEFT([Number],1) 
                              ORDER BY CAST(SUBSTRING([Number],2,2) AS INT) ) AS RN
FROM Table1
)
SELECT 
    MAX(CASE WHEN Letter = 'B' THEN [Number] END) AS B,
    MAX(CASE WHEN Letter = 'I' THEN [Number] END) AS I,
    MAX(CASE WHEN Letter = 'N' THEN [Number] END) AS N,
    MAX(CASE WHEN Letter = 'G' THEN [Number] END) AS G,
    MAX(CASE WHEN Letter = 'O' THEN [Number] END) AS O
FROM CTE
GROUP BY RN

SQL小提琴

于 2013-01-28T21:55:33.143 回答
1

这种类型的数据转换是一个枢纽。有几种方法可以旋转数据。

聚合案例:这使用case表达式和聚合函数来创建列

select 
  max(case when letter = 'b' then number end) B,
  max(case when letter = 'i' then number end) I,
  max(case when letter = 'n' then number end) N,
  max(case when letter = 'g' then number end) G,
  max(case when letter = 'o' then number end) O
from
(
  select left(number, 1) letter,
    number,
    row_number() over(partition by left(number, 1) 
                     order by cast(substring(number, 2, 2) as int)) rn
  from yourtable
) src
group by rn
order by rn

请参阅带有演示的 SQL Fiddle

枢:

或者由于您使用的是 SQL Server 2005+,您可以使用以下PIVOT功能:

select b, i, n, g, o
from
(  
  select left(number, 1) letter,
    number,
    row_number() over(partition by left(number, 1) 
                      order by cast(substring(number, 2, 2) as int)) rn
  from yourtable
) src
pivot
(
  max(number)
  for letter in (b, i, n, g, o)
) piv

请参阅带有演示的 SQL Fiddle

于 2013-01-28T21:55:48.123 回答