我在表格中有这样的数据:
column1 column2
a 1
a 2
b 2
b 3
a 4
c 5
我想要这样的输出:
column1 column2
a 1-2
b 2-3
a 4-0
c 5-0
答案 0 :(得分:2)
尝试此查询:
with vw1 as
(select table1.*,rownum rn from table1),
vw2 as (select col1,col2,rn,rn - col2 dis from vw1),
vw3 as (select col1,min(rn),to_char(min(col2))||' - '||
case when min(col2) = max(col2) then '0' else to_char(max(col2)) end col2 from vw2
group by col1,dis order by min(rn))
select col1,col2 from vw3;
答案 1 :(得分:0)
你还没有给出很多信息
- 对于column1中的每个值,第2列中是否始终只有1或2个值?
- column2总是按顺序排列吗?
- 等等?
但是,对于给定的数据,以下内容应该给出您要求的结果。
SELECT
column1,
MIN(column2) AS first_column2,
CASE WHEN COUNT(*) = 1 THEN 0 ELSE MAX(column2) END AS final_column2
FROM
(
SELECT
ROW_NUMBER() OVER ( ORDER BY column2, column1) AS sequence_main,
ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2 ) AS sequence_c1,
*
FROM
your_table
)
AS sequenced_table
GROUP BY
sequence_main - sequence_c1,
column1
ORDER BY
MIN(sequence_main)
示例计算:
column1 column2 | sequence_main sequence_c1 main - c1 | group
a 1 | 1 1 0 | a1
a 2 | 2 2 0 | a1
b 2 | 3 1 2 | b2
b 3 | 4 2 2 | b2
a 4 | 5 3 2 | a2
c 5 | 6 1 5 | c5
答案 2 :(得分:0)
尝试此查询...
select * from
(
select col1 as column1,case when LEAD(col1 , 1, 0) OVER (ORDER BY col2) = col1
then concat( LEAD(col2 , 1, 0) OVER (ORDER BY col2),'-'||col2)
else (case when lag(col1,1,0) over (ORDER BY col2) <> col1 then
concat(col2,'-'||'0')else '0' end)
end as column2
from table
order by col2
)
where column2<>'0'
;
答案 3 :(得分:0)
你应该小心使用像
这样的东西 select column1, column2, rownum from table1
为您的数据创建一些唯一的ID。每个定义是在SQL 未定义中没有订单的排序。因此巧合的是
select * from table1
以您在数据库中插入的顺序返回行。随着数据的增长,您将获得此排序的例外情况。因此建议高度将主键列放在数据表中以保留此插入顺序。我为此添加了id
列。
使用此pimped数据集,您可以使用此查询获取请求的数据:
with data_aggr as (
select column1,
case
when lead(column1,1,' ') over (order by id)<>column1
and lag(column1,1,' ') over (order by id)<>column1
then column2 || '-0'
when lead(column1,1,' ') over (order by id)=column1
and lag(column1,1,' ') over (order by id)<>column1
then column2 || '-' || lead(column2,1) over (order by id)
else null
end aggr_col2
from table1)
select column1, aggr_col2 from data_aggr where not aggr_col2 is null