我想获得MIN / MAX门牌号,这是一项简单的任务。
但是有一个包含区域的列。
原始数据:
Street Name | House Number | district
Hauptstr. | 1 | A
Hauptstr. | 2 | A
Hauptstr. | 3 | B
Hauptstr. | 4 | B
Hauptstr. | 5 | A
期望输出:
Street Name | House number (FROM) | House number (TO) | district
Hauptstr. | 1 | 2 | A
Hauptstr. | 3 | 4 | B
Hauptstr. | 5 | 5 | A
我的输出:
Street Name | House number (FROM) | House number (TO) | district
Hauptstr. | 1 | 5 | A
Hauptstr. | 3 | 4 | B
我愿意接受意见和建议。我是否需要临时表来处理地址?
提前谢谢。
答案 0 :(得分:1)
您可以使用变量在MySQL中执行此操作。它为相邻街道值的每一行分配一个组:
select street, district, min(housenumber), max(housenumber)
from (select t.*,
(@grp := if(@d = district, @grp,
if(@d := district, @grp + 1, @grp + 1)
)
) as grp
from t cross join
(select @d := '', @grp := 0) params
order by street, housenumber
) t
group by grp, street, district;
答案 1 :(得分:0)
假设您正在开发支持它们的SQL实现,您可以在(未经测试的)
行中使用FIRST_VALUE
和LAST_VALUE
等分析函数
select streetname
,first_value(housenumber) over (order by streetname, housenumber partition by district) as from
,last_value(housenumber) over (order by streetname, housenumber partition by district) as to
,district
from table
编辑:该查询不起作用,但这些内容应该是。
EDIT2:这是一种(有点复杂)的方式
select *
from (
select streetname
,district
,from_num
,coalesce(to_num,lead(to_num,1) over (partition by streetname order by housenumber)) as to_num
from (
select streetname
,housenumber
,district
,case when coalesce(lag(district,1) over (partition by streetname order by housenumber),'') <> district then housenumber end as from_num
,case when coalesce(lead(district,1) over (partition by streetname order by housenumber),'') <> district then housenumber end as to_num
from table
)
where from_num is not null or to_num is not null
)
where from_num is not null
这是在DB2中测试的。我不了解MaxDB,因此您可能需要调整语法。 至于发生了什么的解释: