给梦一个奔跑的方向!
PDF Print E-mail
User Rating: / 2
PoorBest 
Written by xlingfairy
Thursday, 21 May 2009 17:57
 06年,司令做Oracle的时候,对分析函数表现出了极大兴趣。于是有了下面这些日志:
 
不要怀疑,司令就是我啦。
 
SQLServer 我只是05年用过一年,除了06年,我都是在用MySQL。
现在没机会用Oracle ,但是却一直梦着它,梦想着某一天在用上它。
 
SQLServer 2005 里面也提供了分析函数,有叫窗口函数的。
看下面的示例:
 
SELECT
RP.ProductID,
RP.RetailerProductID,
RP.RetailerPrice,
R.RetailerName
FROM
CSK_Store_RetailerProduct RP LEFT JOIN
CSK_Store_Retailer R ON RP.RetailerID = R.RetailerID
WHERE
RP.RetailerProductStatus = 1
AND R.Retailerstatus = 1
AND (RP.RetailerPrice > 1 OR RP.RetailerPrice <0)
ORDER BY
ProductID,RetailerPrice ASC
 
图1
 
 
得出的结果,每个ProductID 都有N个记录,我的目的是取出每组RetailerPrice 最小的那特条记录,用Group by 吧,那要写更多的代码出来(因为 retailerProductID 不一样,直接在上面的 order by 前面加 Group by 肯定是错误的数据,非得在套一层查询出来,用 productID 和 retailerPrice 来关联才行)
 
用SQLServer 2005 的分析函数,上面的问题就太简单了!
SELECT
ROW_NUMBER() OVER (PARTITION BY RP.ProductID ORDER BY RP.RetailerPrice) AS ROWNUM,
RP.ProductID,
RP.RetailerProductID,
RP.RetailerPrice,
R.RetailerName
FROM
CSK_Store_RetailerProduct RP LEFT JOIN
CSK_Store_Retailer R ON RP.RetailerID = R.RetailerID
WHERE
RP.RetailerProductStatus = 1
AND R.Retailerstatus = 1
AND (RP.RetailerPrice > 1 OR RP.RetailerPrice <0)
ORDER BY
ProductID,RetailerPrice ASC
 
图2
 
下面还要在做什么操作,就不用在说了吧!
另外要说一下,如果把:
ROW_NUMBER() OVER (PARTITION BY RP.ProductID ORDER BY RP.RetailerPrice)
写到 WHERE里,就会报错,因为窗口函数只能写在 SELECT 或 ORDER BY 子句里。
 
Last Updated ( Thursday, 21 May 2009 18:09 )
 

Add comment


Security code
Refresh

Popular Contents

Recommend

Site Info

Members : 1
Content : 130
Web Links : 7
Content View Hits : 99684

Links