DENSE_RANK()排名筛选 名次出错? 如100条数据 排名是从1到100 现在我根据条件Where一下 查询到的名称就不是原来的那个名次了?请问如何才能查询到原名次?谢谢
------解决方案--------------------
DENSE_RANK()是对查询结果排名,如果查询结果变化了,那排名也就变化了。如果想使用排名作条件,可以使用子查询:
SELECT *
FROM (
SELECT DENSE_RANK() AS NUM,*
FROM TB
)
WHERE NUM=3
------解决方案--------------------
如果你直接對原來的語句做where的話是對你where篩選後的語句重新進行排名的,如果要對排名後的數據再篩選可使用類似下面的語句
USE AdventureWorks2012;
GO
WITH a AS(
SELECT i.ProductID, p.Name, i.LocationID, i.Quantity
,DENSE_RANK() OVER
(PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS Rank
FROM Production.ProductInventory AS i
INNER JOIN Production.Product AS p
ON i.ProductID = p.ProductID
--WHERE i.LocationID BETWEEN 3 AND 4
)
SELECT * FROM a WHERE a.productid BETWEEN 367 AND 389
GO
------解决方案--------------------
/************************************************************
* Code formatted by SoftTree SQL Assistant ?v6.5.278
* Time: 2014/4/11 星期五 上午 11:51:25
************************************************************/
USE AdventureWorks2012;
GO
WITH a AS(
SELECT i.ProductID,
p.Name,
i.LocationID,
i.Quantity,
ROW_NUMBER() OVER(PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS
RANK,
COUNT(1) OVER(PARTITION BY i.LocationID) AS COUNT
FROM Production.ProductInventory AS i
INNER JOIN Production.Product AS p
ON i.ProductID = p.ProductID
--WHERE i.LocationID BETWEEN 3 AND 4
)
SELECT CASE
WHEN CONVERT(DECIMAL(18, 2), [rank]) / [COUNT] <= 0.2 THEN N'1等'
WHEN CONVERT(DECIMAL(18, 2), [rank]) / [COUNT] <= 0.8 AND CONVERT(DECIMAL(18, 2), [rank])
/ [COUNT] > 0.2 THEN N'2等'
ELSE N'3等'
END,
CONVERT(DECIMAL(18, 2), [rank]) / [count],
*
FROM a
GO
我用示例資料庫的內容做個範例給你參考吧