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

标签 java sql sql-server pivot unpivot

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

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/

相关文章:

java - JAX-WS复杂对象

mysql - SQL:选择在另一个表中不具有值的 ID/值组合

sql - 比较相同 ID 的两个最近的列

mysql - SQL Server 到 MySQL 函数在值中使用撇号、引号和逗号

java - 降低类和方法的可见性

java - 空字符串末尾有 "\u0000"

java - 无法将类型 'java.lang.String' 的属性值转换为属性 'com.mongodb.ServerAddress[]' 所需的类型 'replicaSetSeeds'

php - 在 MySQL 中删除后自动增量不正确 ID 值

sql - 根据字符修剪字符串

字符串文字中的 SQLite 绑定(bind)