Sql Query将一系列数字分组为低和高

时间:2009-10-08 13:53:44

标签: sql-server

我有一个类似于下面的表

street_id | address_number | address_direction | address_street | address_type ...
----------------------------------------------------------------------------------
1         | 121            | W                 | Fake           | St
1         | 131            | W                 | Fake           | St
1         | 200            | W                 | Fake           | St
2         | 321            | N                 | Fake           | St
2         | 131            | N                 | Fake           | St
2         | 500            | N                 | Fake           | St

任何人都可以帮我提出一个可以帮助我显示如下数据的查询吗?

street_id | address_low_range | address_high_range | address_direction | address_street | address_type ...
----------------------------------------------------------------------------------
1         |  121              | 200                | W                 | Fake           | St
2         |  131              | 500                | N                 | Fake           | St   

提前致谢

5 个答案:

答案 0 :(得分:2)

select
       street_id,
       direction,
       min(address_number) as address_low_range,
       max(address_number) as address_high_range
       address_street,
       address_type
from mytable
group by address_id, address_street, direction;

顺便说一句,为什么你的表中的address_street和address_type可以说是street_id所指的那个?

答案 1 :(得分:2)

你可以使用Min(address_number)和Max(address_number)来选择低和高范围,然后按street_id,address_direction,address_street,address_type进行分组:

SELECT 
street_id, 
Min(address_number) as address_low_range,
Max(address_number) as address_high_range,
address_direction, 
address_street, 
address_type
FROM table_name
GROUP BY street_id, address_direction, address_street, address_type

答案 2 :(得分:1)

脱离我的头顶:

select street_id, min(address_number), max(address_number), address_direction
from addresses
group by street_id, address_direction

答案 3 :(得分:1)

您可以测试此查询吗

    select street_id, MIN(address_number) add_low,
MAX(address_number) add_high FROM your_table
Group by street_id

答案 4 :(得分:1)

在您想要最小或最大的列上使用MIN()MAX()聚合函数。确保在GROUP BY子句中包含其他列。