ROW_NUMBER个计数返回无效结果

时间:2018-12-14 13:41:46

标签: sql sql-server

我是SQL Server的新手,正努力提高自己。我准备了一条声明来获取被取消的客户(其中customerCancel为true)

通常,当我计算已取消客户的总数时,总数为1050。

我想要显示的是前100个用户,但是当我运行下面的查询时,我只有38个,当我手动增加RowNumber时,结果在增加,但与实际结果不同。我将使用此查询进行分页。

我的查询:

SELECT
   COUNT(*) OVER() TotalRowCount,
   ID, customerNo, customerName, customerSurname, customerTitle, customerUnitList, customerTotalList 
FROM
   (SELECT
        ROW_NUMBER() OVER(ORDER BY m.ID) RowNumber, 
        COUNT(*) OVER() TotalRowCount,
        m.ID, m.customerNo, m.customerName, m.customerSurname, m.customerTitle,
        (SELECT COUNT(f.ID) 
         FROM Invoices f 
         WHERE f.Paid = 0 
           AND f.custumerCancel = 0 
           AND f.customerID = m.ID) AS customerUnitList,
        COALESCE((SELECT SUM(f.Total) AS InvoiceNo
                  FROM Invoices f 
                  WHERE f.Paid = 0 
                    AND f.custumerCancel = 0 
                    AND f.customerID = m.ID), 0) AS customerTotalList 
    FROM
        Customers m) flist 
WHERE
   customerTotalList > 0 
   AND RowNumber between 1 AND 100

我尝试了几种方法来修复它,但是没有运气。

3 个答案:

答案 0 :(得分:3)

尝试此查询

SELECT * FROM   (SELECT Count(*) OVER()   TotalRowCount, 
               Row_number() 
                 OVER(ORDER BY id) RowNumber, 
               id, 
               customerno, 
               customername, 
               customersurname, 
               customertitle, 
               customerunitlist, 
               customertotallist 
        FROM   (SELECT m.id, 
                       m.customerno, 
                       m.customername, 
                       m.customersurname, 
                       m.customertitle, 
                       (SELECT Count(f.id) 
                        FROM   invoices f 
                        WHERE  f.paid = 0 
                               AND f.custumercancel = 0 
                               AND f.customerid = m.id)            AS 
                       customerUnitList, 
                       Isnull((SELECT Sum(f.total) AS InvoiceNo 
                               FROM   invoices f 
                               WHERE  f.paid = 0 
                                      AND f.custumercancel = 0 
                                      AND f.customerid = m.id), 0) AS 
                       customerTotalList 
                FROM   customers m) flist 
        WHERE  customertotallist > 0) x 
WHERE  rownumber BETWEEN 1 AND 100 

仅在应用所有自定义过滤器后,才应将行号过滤器应用于分页。

答案 1 :(得分:0)

使用row_number()的WHERE外部 创建查询意味着某些行可能被该行过滤。我敢打赌,如果您注释掉最后一个(customerTotalList>0)之前的行,您将始终获得100行。

如果要100,就可以使用

select top 100..........order by RowNumber asc

答案 2 :(得分:0)

您拥有哪个版本的MS SQL Server?这种旧方法在MS SQL Server 2012之前可用,从2012年开始,您可以使用0FFSET FETCH进行分页。