gpt4 book ai didi

java - 如何将不同列的值分组到一行中?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:48:28 25 4
gpt4 key购买 nike

我有一个如下所示的源表:

enter image description here

如何使结果表看起来像这样。我可以在 sql 或 java 代码中使用解决方案。

enter image description here

拜托,谁能帮帮我。谢谢。

最佳答案

我认为最简单的方法是同时应用 UNPIVOTPIVOT 函数来获得结果:

select account, description,
[value_1], [value_2], [value_3], [value_4]
from
(
select account, description, col, value,
row_number() over(partition by account, col order by col) rn
from
(
select [account], [description], [value_1], [value_2], [value_3], [value_4]
from yourtable
) src
unpivot
(
value
for col in ([value_1], [value_2], [value_3], [value_4])
) un
) s
pivot
(
max(value)
for col in ([value_1], [value_2], [value_3], [value_4])
) piv

参见 SQL Fiddle with Demo .

这也可以使用 UNION ALL 作为 unpivot 和聚合函数以及 CASE 表达式来完成:

select account, description,
max(case when col = 'value_1' then value end) value_1,
max(case when col = 'value_2' then value end) value_2,
max(case when col = 'value_3' then value end) value_3,
max(case when col = 'value_4' then value end) value_4
from
(
select account, description, col, value,
row_number() over(partition by account, col order by account) rn
from
(
select [account], [description], 'value_1' col, [value_1] value
from yourtable
where [value_1] is not null
union all
select [account], [description], 'value_2' col, [value_2] value
from yourtable
where [value_2] is not null
union all
select [account], [description], 'value_3' col, [value_3] value
from yourtable
where [value_3] is not null
union all
select [account], [description], 'value_4' col, [value_4] value
from yourtable
where [value_4] is not null
) s
) un
group by account, description, rn

参见 SQL Fiddle with Demo

两者都给出结果:

| ACCOUNT |  DESCRIPTION |  VALUE_1 |  VALUE_2 |  VALUE_3 |  VALUE_4 |
----------------------------------------------------------------------
| A00005 | Account Desc | ABCD0081 | BCDE0010 | BKCP0010 | SMTP0010 |
| A00005 | Account Desc | ABCD0082 | (null) | BKCP0011 | (null) |

关于java - 如何将不同列的值分组到一行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com