在此希望一些這可能是一般可重複使用:
;with startingRS (productid, product, orderid, ordercountry) as (
select 1, 'Chocolate', 1, 'uk' union all
select 2, 'Banana', 2, 'uk' union all
select 2, 'Banana', 3, 'usa' union all
select 3, 'Strawberry', 4, 'usa'
), countryRankings as (
select productid,product,orderid,ordercountry,
RANK() over (PARTITION by productid ORDER by ordercountry) as FirstCountry,
RANK() over (PARTITION by productid ORDER by ordercountry desc) as LastCountry
from
startingRS
), singleCountry as (
select productid,product,orderid,ordercountry
from countryRankings
where FirstCountry = 1 and LastCountry = 1
)
select * from singleCountry where ordercountry='uk'
在startingRS中,您將當前必須提供的任何查詢生成所顯示的中間結果。 countryRankings CTE增加了兩個新列,這些列對每個產品中的國家進行排名。
singleCountry CTE將結果集減少到那些國家作爲產品中第一個也是最後一個國家(即該產品只有一個國家)的結果。最後,我們查詢那些來自英國的結果。
如果你想要的,例如,與原產地的一個國家所有的productid行,你就跳過這最後的where子句(和你會在你的結果也讓3,草莓,4,USA)
所以你有一個當前查詢,看起來像:
select p.productid,p.product,o.orderid,o.ordercountry
from product p inner join order o on p.productid = o.productid --(or however these joins work for your tables)
那麼你已經重寫了第一CTE爲:
;with startingRS (productid, product, orderid, ordercountry) as (
select p.productid,p.product,o.orderid,o.ordercountry
from product p inner join order o on p.productid = o.productid
), /* rest of query */
將返回`香蕉',這是不會被退回 – AakashM 2011-02-04 15:04:44
對不起 - 這返回有美國訂單的產品行 - 我需要過濾掉這一行(和其他人喜歡它在我的真實數據集中...) – 2011-02-04 15:12:26