ROW_NUMBER()返回值不一致

时间:2011-05-30 10:49:23

标签: sql-server-2005 row-number

我在ASP.NET中使用ROW_NUM()函数进行分页

SELECT row_num, expense_id,email, reason, amount,date,category_name,is_income
FROM
  (
  SELECT e.expense_id,e.email, e.reason, e.amount,e.date,c.category_name,e.is_income, 
  ROW_NUMBER() OVER(ORDER BY e.date DESC,e.expense_id) as row_num
  FROM Expense e
  JOIN Category c ON e.category_id = c.category_id
  WHERE e.date >='5-1-2011' AND e.date<='5-31-2011'
  ) as ExpenseInfo
WHERE email='sample@domain.com'

但它返回了一个不一致的row_num列表(例如1,3,4 ......或2,3,4 ......)。我该如何解决这个问题?

提前致谢。

我已经解决了我的问题

SELECT RowNum, expense_id, email, reason, amount, date, category_name, is_income
FROM
(
SELECT e.expense_id, e.email, e.reason, e.amount, e.date, c.category_name, e.is_income, Row_Number() OVER(ORDER BY date DESC) as row_num 
FROM Expense e JOIN Category c 
  ON e.category_id = c.category_id
WHERE e.date >='5-1-2011' AND e.date<='5-31-2011' AND e.email='sample@domain.com'
) AS ExpenseInfo
WHERE row_num>=1 and row_num<=20

2 个答案:

答案 0 :(得分:2)

在主查询中添加ROW_NUMBER。在子查询中添加它时,首先生成数字,然后过滤记录。当您在最终结果上生成行号时,您将不会遇到此问题。

select
  s.*,
  row_number() over(order by s.date desc, s.expense_id) as row_num
from
  (
   /*YourQueryWithAllItsConditions*/
  ) s

答案 1 :(得分:0)

Where email = 'sample@domain.com'过滤掉某些行。对于你在这里做的事情,你不需要“外部”查询。把它们包在一起吧。

 SELECT ROW_NUMBER() OVER(ORDER BY e.date DESC, e.expense_id) as row_num
       , e.expense_id
       , e.email
       , e.reason
       , e.amount
       , e.date
       , c.category_name
       , e.is_income
  FROM Expense e
  JOIN Category c 
    ON e.category_id = c.category_id
  WHERE e.date >='5-1-2011' 
    AND e.date <='5-31-2011'
    AND e.email = 'sample@domain.com'