1

我正在尝试使用 MS SQL 实现 LIMIT OFFSET 查询,以便在网站上与 PHP 和 PDO 一起实现对我的产品的分页,但我收到以下错误:“列名无效”

我的查询

SELECT OITM.ItemCode,OITM.ItemName,ITM1.Price , 
OITM.CardCode,ROW_NUMBER() OVER (ORDER BY OITM.ItemName DESC) AS RNumber 
FROM OITM INNER JOIN OCRD ON OCRD.CardCode = OITM.CardCode 
INNER JOIN ITM1 ON OITM.ItemCode = ITM1.ItemCode 
WHERE OITM.frozenFor='N' AND PriceList=1 AND U_Publish='Y' 
AND RNumber >= 1 AND RNumber <= 2

不确定这里有什么问题

4

2 回答 2

2

您不需要HAVING子句。您可以使用 cte 函数或子查询。像这样:

;WITH CTE
AS
(
    SELECT OITM.ItemCode,OITM.ItemName,ITM1.Price , 
    OITM.CardCode,ROW_NUMBER() OVER (ORDER BY OITM.ItemName DESC) AS RNumber 
    FROM OITM INNER JOIN OCRD ON OCRD.CardCode = OITM.CardCode 
    INNER JOIN ITM1 ON OITM.ItemCode = ITM1.ItemCode 
    WHERE OITM.frozenFor='N' AND PriceList=1 AND U_Publish='Y' 
)
SELECT
    *
FROM
    CTE
WHERE
    RNumber >= 1 AND RNumber <= 2

或者使用这样的子查询:

SELECT
    *
FROM
    (
        SELECT OITM.ItemCode,OITM.ItemName,ITM1.Price , 
        OITM.CardCode,ROW_NUMBER() OVER (ORDER BY OITM.ItemName DESC) AS RNumber 
        FROM OITM INNER JOIN OCRD ON OCRD.CardCode = OITM.CardCode 
        INNER JOIN ITM1 ON OITM.ItemCode = ITM1.ItemCode 
        WHERE OITM.frozenFor='N' AND PriceList=1 AND U_Publish='Y' 
    ) AS t
WHERE
    t.RNumber >= 1 AND t.RNumber <= 2
于 2012-05-04T08:15:56.613 回答
0

您不能在 Where 条件中使用新定义的名称,您必须放入 HAVING 子句。

SELECT OITM.ItemCode,OITM.ItemName,ITM1.Price , 
OITM.CardCode,
ROW_NUMBER() OVER (ORDER BY OITM.ItemName DESC) AS RNumber 
FROM OITM INNER JOIN OCRD ON OCRD.CardCode = OITM.CardCode 
INNER JOIN ITM1 ON OITM.ItemCode = ITM1.ItemCode 
WHERE OITM.frozenFor='N' AND PriceList=1 AND U_Publish='Y' 
HAVING RNumber >= 1 AND RNumb
于 2012-05-04T08:11:04.883 回答