將範圍分組到範圍 (Group a range towards a range)


問題描述

將範圍分組到範圍 (Group a range towards a range)

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!

‑‑‑‑‑

參考解法

方法 1:

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;

(by TwisterXSebastian Meine)

參考文件

  1. Group a range towards a range (CC BY‑SA 3.0/4.0)

#sql-server-2008 #group-by #stored-procedures






相關問題

基於集合的插入到具有 1 到 0-1 關係的兩個表中 (Set based insert into two tables with 1 to 0-1 relation)

如何使用 CTE 從分層視圖中獲取元素 (How to get elements from a hierarchical view with CTE)

where 子句中使用等於和 IN 的 CASE 語句 (CASE Statement in where clause using equal to and IN)

與 SQL 服務器匯總匯總 - 但只有最後一個摘要? (Sum with SQL server RollUP - but only last summary?)

將範圍分組到範圍 (Group a range towards a range)

在 SQL Server 2008 中運行 WHILE 或 CURSOR 或兩者 (Running WHILE or CURSOR or both in SQL Server 2008)

按組中的最大值排序 (Order by the max value in the group)

使用存儲過程創建搜索函數 (Creating a Search Function, using stored procedure)

在 sql server 2008 中查詢最後費用日期 (Query for Last Fees Date in sql server 2008)

除了 SQL Server Profiler,還有什麼 SQL Server Profile? (What is SQL Server Profile aside from SQL Server Profiler?)

什麼是日期時間2? (What is datetime2?)

可以在這裡使用 Common Table 表達式來提高性能嗎? (Can Common Table expressions be used here for performance?)







留言討論