我有这个 sql 结果
color red AA
color red BB
color red CC
color blue DD
color blue EE
有没有办法按列合并,以获得以下结果?
color red AA
BB
CC
blue DD
EE
我有这个 sql 结果
color red AA
color red BB
color red CC
color blue DD
color blue EE
有没有办法按列合并,以获得以下结果?
color red AA
BB
CC
blue DD
EE
这通常是您在应用程序的表示层上执行的操作,但如果您想在 SQL 中执行此操作,您可以使用row_number()
:
select
case when col1rn = 1 then col1 else '' end col1,
case when col2rn = 1 then col2 else '' end col2,
col3
from
(
select col1, col2, col3,
row_number() over(partition by col1 order by col1, col2, col3) col1rn,
row_number() over(partition by col1, col2 order by col1, col2, col3) col2rn
from yt
) d;
请参阅SQL Fiddle with Demo。你可以from yt
用你的查询替换,给出结果:
| COL1 | COL2 | COL3 |
-----------------------
| color | blue | DD |
| | | EE |
| | red | AA |
| | | BB |
| | | CC |
| test | blue | CC |
| | red | AA |
| | | BB |
Here we are using a ranking function to find your redundant data, and then a case
can blank it out as necessary. Note also that we're handling multiple "categories" or "groups" or whatever you happen to be partitioning by in your real data (shown as columns a
and b
here).
;with cte as (
select 'color' as a, 'red' as b, 'AA' as c
union all select 'color', 'red', 'BB'
union all select 'color', 'red', 'CC'
union all select 'color', 'blue', 'DD'
union all select 'color', 'blue', 'EE'
union all select 'smell', 'bad', 'AA'
union all select 'smell', 'bad', 'BB'
union all select 'smell', 'bad', 'CC'
union all select 'smell', 'good', 'DD'
union all select 'smell', 'good', 'EE'
)
select case when row_number() over (partition by a order by b, c) = 1 then a else '' end as ColA
, case when row_number() over (partition by a, b order by c) = 1 then b else '' end as ColB
, c as ColC
from cte
order by a, b, c
This will yield the following result:
ColA ColB ColC
----- ---- ----
color blue DD
EE
red AA
BB
CC
smell bad AA
BB
CC
good DD
EE