从多行创建1条记录

时间:2014-01-17 15:48:18

标签: sql sql-server pivot-table

我正在尝试组合来自具有公共标识符的单个表的多个行。 因此,在下面的示例中,GroupIdentifier的{​​{1}}变为1111111111111记录,每条记录都包含在1中。 某些记录可能会将sub Field_#个结果合并到3,但有些记录可能只有11

由于

样本数据

2

预期产出:

GroupIdentifier UniqueIdentifier    Direction   UserID

1111111111111   123456789       1           98685
1111111111111   123456790       2           4469
1111111111111   123456856       1           98685
1111115555555   123458765       2           5435
2222225353535   123454321       1           6565
2222225353535   123458765       3           4444

2 个答案:

答案 0 :(得分:3)

这是一个“多列支点”。最简单的方法是使用GROUP BY和MIN(CASE ..)手动完成,但如果您的设计发生变化,它也是最不灵活的。

WITH t AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY GroupIdentifier ORDER BY DateTime ) AS SortOrder FROM MyTable)
SELECT
  GroupIdentifier,
  MIN(CASE SortOrder WHEN 1 THEN UniqueIdentifier END) UniqueIdentifier_1,
  MIN(CASE SortOrder WHEN 1 THEN Direction        END) Direction_1,
  MIN(CASE SortOrder WHEN 1 THEN UserID           END) UserID_1,
  MIN(CASE SortOrder WHEN 2 THEN UniqueIdentifier END) UniqueIdentifier_2,
  MIN(CASE SortOrder WHEN 2 THEN Direction        END) Direction_2,
  MIN(CASE SortOrder WHEN 2 THEN UserID           END) UserID_2,
  MIN(CASE SortOrder WHEN 3 THEN UniqueIdentifier END) UniqueIdentifier_3,
  MIN(CASE SortOrder WHEN 3 THEN Direction        END) Direction_3,
  MIN(CASE SortOrder WHEN 3 THEN UserID           END) UserID_3
) FROM t
GROUP BY GroupIdentifier

答案 1 :(得分:0)

你可以使用这样的东西。 with命令为1,2,3等

with x
as
( select GroupIdentifier
  ,      UniqueIdentifier
  ,      Direction
  ,      rank() over (partition by GroupIdentifier order by Direction) index
  from   TABLE_NAME
)
select one.GroupIdentifier
,      one.UniqueIdentifier UniqueID_1
,      one.Direction UniqueDirection_1
,      one.UserID UserID_1
,      two.UniqueIdentifier UniqueID_2
,      two.Direction UniqueDirection_2
,      two.UserID UserID_2
,      three.UniqueIdentifier UniqueID_3
,      three.Direction UniqueDirection_3
,      three.UserID UserID_3
from   x one
left
outer
join   x two
on     one.GroupIdentifier = two.GroupIdentifier
and    two.index = 2
left
outer
join   x three
on     one.GroupIdentifier = three.GroupIdentifier
and    three.index = 3
where  one.index = 1