我正在修改查询以在其中包含分页和rownum计数,但是不知何故rownum导致错误
列名模糊
代码:
WITH List AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY error_type asc) AS rowNum,
MAX(id) AS id,
COUNT(errorid) AS ecount,
MAX(errorid) AS errorid,
FORMAT(MAX(datein), 'MMMM d, yyyy h:mm:ss tt PST', 'en-US') AS max_datein,
template,
line,
error_message,
UPPER(error_type) AS error_type
FROM
mytable mt
GROUP BY
errorid,
template,
line,
error_message,
error_type
),
ListRecordCount AS
(
SELECT
*
FROM
List,
(
SELECT
MAX(rowNum) AS TotalrecordCount
FROM List
) AS TotalrecordCount
)
SELECT *
FROM
ListRecordCount
INNER JOIN List mi ON mt.id = mi.id
WHERE rowNum BETWEEN 1 and 5000
ORDER BY mi.max_datein
我得到的错误是:
[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]无法绑定多部分标识符“ mt.id”。 (4104)
[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]模棱两可的列名“ rowNum”。 (209)
[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]模棱两可的列名“ rowNum”。 (209)
答案 0 :(得分:1)
因为首先在List表中指定rowNum,然后从List中选择*以创建ListRecordCount表,该表在此还包括rowNum列。因此,如果将ListRecordCount与List结合使用,则两个表中都将具有rowNum,这将导致模棱两可。
同样从上面的查询中,我看不到您将这两个表联接的原因。
我相信这个查询就是您想要的。
WITH List AS(
SELECT
row_number() over(ORDER BY error_type asc) AS rowNum
, max(id) as id, count(errorid) as ecount
, max(errorid) as errorid, FORMAT(max(datein), 'MMMM d, yyyy h:mm:ss tt PST', 'en-US') as max_datein
, template,line,error_message, upper(error_type) AS error_type
from mytable mt
group by errorid, template,line,error_message,error_type
),
ListRecordCount AS(
SELECT
*
, (SELECT MAX(rowNum) AS TotalrecordCount FROM List) AS TotalrecordCount
FROM List
)
SELECT *
FROM ListRecordCount
WHERE rowNum BETWEEN 1 and 5000
order by max_datein
答案 1 :(得分:0)
您在两个表中都指定了row_num
。也许您打算这样做:
select . . .
from ListRecordCount lrc join
List mi
on mt.id = mi.id
where lrc.rowNum between 1 and 5000
或:
select . . .
from ListRecordCount lrc join
List mi
on mt.id = mi.id
where mi.rowNum between 1 and 5000
或者,如果您想要基于结果集的行号:
select *
from (select . . ., row_number() over (order by ?) as seqnum
from ListRecordCount lrc join
List mi
on mt.id = mi.id
) mil
where seqnum between 1 and 5000
答案 2 :(得分:0)
该错误涉及您的主要SELECT
子句:
SELECT *
FROM
ListRecordCount
INNER JOIN List mi ON mt.id = mi.id
WHERE rowNum BETWEEN 1 and 5000
^^
问题出在以下事实:公用表表达式ListRecordCount
和List
都有一个名为rowNum
的列(稍后会详细介绍)。
要解决此问题,您只需在主查询中添加前缀列rowNum
。它必须是mt.rowNum
或mi.rowNum
,例如:
...
SELECT
*
FROM
ListRecordCount mt
INNER JOIN List mi ON mt.id = mi.id
WHERE mt.rowNum BETWEEN 1 and 5000
ORDER BY mi.max_datein
Nb:您似乎缺少了mt
上ListRecordCount
别名的声明,我添加了它。
详细信息
List
定义了rowNum
列:
WITH List AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY error_type asc) AS rowNum,
...
ListItems
在SELECT *
上进行了List
,因此它也有列rowNum
:
...
ListRecordCount AS
(
SELECT
*
FROM
List,
...