如果Price Range
ID是上升爲價格那麼你可以簡單:
SELECT p.ID,
p.Name,
MAX(pr.ID) as PriceRangeID
FROM Product p
LEFT JOIN PriceRange pr
ON p.Price >= pr.Price
GROUP BY p.ID, p.Name
輸出:
ID Name PriceRangeID
----------- ----- ------------
1 Prod1 NULL
2 Prod2 1
3 Prod3 1
4 Prod4 1
5 Prod5 2
6 Prod5 2
7 Prod6 3
Warning: Null value is eliminated by an aggregate or other SET operation.
(7 row(s) affected)
新的CTE的另一種方式:
;WITH new_price_range AS (
SELECT pr1.ID,
MAX(pr1.Price) as PriceB,
MIN(ISNULL(pr2.Price-1,pr1.Price*10)) as PriceT
FROM PriceRange pr1
LEFT JOIN PriceRange pr2
ON Pr1.Price < Pr2.Price
GROUP BY pr1.ID)
SELECT p.ID,
p.Name,
pr.ID as PriceRangeID
FROM Product p
LEFT JOIN new_price_range pr
ON p.Price between pr.PriceB and pr.PriceT
在這種CTE我們產生這樣的:
ID PriceB PriceT
----------- ----------- -----------
1 10 49
2 50 99
3 100 1000
(3 row(s) affected)
輸出:
ID Name PriceRangeID
----------- ----- ------------
1 Prod1 NULL
2 Prod2 1
3 Prod3 1
4 Prod4 1
5 Prod5 2
6 Prod5 2
7 Prod6 3
(7 row(s) affected)
那麼,你的問題是什麼? – qxg
我的問題是使用sql join來獲取結果數據集。它不能用簡單的左連接完成, –