Sql 从多行中创建一条记录
我正在尝试合并单个表中具有公共标识符的多行。 因此,在下面的示例中,Sql 从多行中创建一条记录,sql,sql-server,pivot-table,Sql,Sql Server,Pivot Table,我正在尝试合并单个表中具有公共标识符的多行。 因此,在下面的示例中,1111111的GroupIdentifier变为1记录,每个记录都包含在子字段中。 有些记录可能有3结果,这些结果被合并成1,但有些记录可能只有1或2 谢谢 样本数据 GroupIdentifier UniqueIdentifier Direction UserID 1111111111111 123456789 1 98685 1111111111111 123456790
1111111
的GroupIdentifier
变为1
记录,每个记录都包含在子字段中。
有些记录可能有3
结果,这些结果被合并成1
,但有些记录可能只有1
或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
预期产出:
GroupIdentifier UniqueID_1 UniqueDirection_1 UserID_1 UniqueID_2 UniqueDirection_2 UserID_2 UniqueID_3 UniqueDirection_3 UserID_3
1111111111111 123456789 1 98685 123456790 2 4469 123456856 1 98685
1111115555555 123458765 2 5435
2222225353535 123454321 1 6565 123458765 3 4444
你可以用这样的东西。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
这是一个“多列轴心”。最简单的方法是使用GROUPBY和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-2-3还是这么灵活呢?在使用这个结果集的任何东西中(例如,另一种更倾向于格式和外观,而不是数据的语言),几乎总是更容易进行这种类型的透视(这可能是您想要获得更有意义的搜索结果的术语)这种数据操作方式的通用术语是PIVOT。读一读:-欢迎来到烦人的旋转世界…废话!我讨厌Excel中的透视表,现在我也必须在SQL中使用它们:(:(@MarkD:PIVOT对我来说,在这种情况下,最让人恼火的是你一次只能旋转一列。我尝试过做类似的事情,但没有成功。方向不一定是有序的,有时可能有1,有时有1,有时有1,有时有2,有时有2,1,1。这太疯狂了。你现在是我最要好的朋友。这就像一个例子一样champ!我不知道你所说的“最不灵活”是什么意思,但从语法的角度来看,我更喜欢这种方法,比如说,多个连接。@AndriyM所说的“不灵活”,我的意思是,琐碎的设计更改会导致代码的多次更改。