将范围分组到一个范围 [英] Group a range towards a range

查看:115
本文介绍了将范围分组到一个范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表:

  tblUnit(ID,名称,PriceFrom,PriceTo)

1,奥迪170,340
2,宝马250,290
3,福特275,500 $ b $ 4,起亚110,250 $ b $ 5,大众135, 460

然后我有这样的预定义价格区间:

  tblPriceRange(ID,PriceFrom,PriceTo)

1,0,100
2,100,200
3, 200,300
4,300,400
5,400,1000

我正在计算在一个或多个价格范围内存在的车辆数量。宝马仅在1档,而奥迪在3档,福特在3档。我之后的结果应该如下所示:

  VehiclesPerRange:
(RangeFrom,RangeTo,NoVehicles)
0,100,0
100,200,3
200,300,5
300,400,3
400,1000,2

我已阅读了许多论坛和其他地方关于按范围分组的帖子。但这些例子都集中在1个单一的价格上,这些价格应该按照一个范围来分组。我知道如何通过连接等来实现这一点,但我无法弄清楚如何编写SQL来将范围分组到一个范围。



任何建议都非常感谢! 你想用加入 tblUnit tblPriceRange 匹配范围重叠的行。如果第二个的开始位置在第一个的开始位置和第一个的开始位置之间,那么两个范围重叠,因此您的连接条件如下所示:

  SELECT * 
FROM dbo.tblUnit u
JOIN dbo.tblPriceRange p
ON u.PriceFrom< p.PriceTo
和p.PriceFrom< u.PriceTo

之后,您只需对其进行分组并计数:

  SELECT PriceFrom,PriceTo,COUNT(1)
FROM(
SELECT p.PriceFrom,p.PriceTo
FROM dbo。 tblUnit u
JOIN dbo.tblPriceRange p
ON u.PriceFrom< p.PriceTo
AND p.PriceFrom< u.PriceTo
)X
GROUP BY PriceFrom ,PriceTo;


I have a table:

tblUnit (ID, Name, PriceFrom, PriceTo)

1, Audi, 170, 340
2, BMW,  250, 290
3, Ford, 275, 500
4, Kia,  110, 250
5, VW,   135, 460

And then I have predefined price ranges like this:

tblPriceRange(ID, PriceFrom, PriceTo)

1,   0,  100
2, 100,  200
3, 200,  300
4, 300,  400
5, 400, 1000

I am trying to count the number of vehicles that exists within one or more price ranges. BMW is only in 1 range, while Audi is in 3 ranges and Ford is in 3.

The result I am after should look something like this:

VehiclesPerRange:
(RangeFrom, RangeTo, NoVehicles)
  0, 100,  0
100, 200,  3
200, 300,  5
300, 400,  3
400, 1000, 2

I have read through lots of posts on this forum and elsewhere about grouping by a range. But those examples are focused on 1 single price that should be grouped towards a range. I understand how to do this via a join etc., but I cant figure out how to write SQL to group a range towards a range.

Any suggestions is highly appreciated!

解决方案

You want to join tblUnit with tblPriceRange matching rows where the ranges overlap. Two ranges overlap if the begin of the second is before the end of the first and the begin of the first before the end of the second, so your join condition would look like this:

SELECT *
FROM dbo.tblUnit u
JOIN dbo.tblPriceRange p
ON u.PriceFrom < p.PriceTo
AND p.PriceFrom < u.PriceTo

After that you just have to group and count:

SELECT PriceFrom, PriceTo, COUNT(1)
FROM(
    SELECT p.PriceFrom, p.PriceTo
    FROM dbo.tblUnit u
    JOIN dbo.tblPriceRange p
    ON u.PriceFrom < p.PriceTo
    AND p.PriceFrom < u.PriceTo
)X
GROUP BY PriceFrom, PriceTo;

这篇关于将范围分组到一个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆