我使用MSSQL相当新,遇到了一个奇怪的问题。给定上一个查询的第一个记录ID,我需要找到之前的50行,它们符合与第一个查询相同的条件,并按降序返回。这是一个ASP.NET站点,我很确定ASP方面是正确的但是当我尝试运行SQL查询时它会给出错误的结果
这是我一直在尝试的SQL
WITH PreviousPosts AS
(
SELECT *
FROM [database].[dbo].[table]
WHERE (A_1STNAME LIKE '(variable)%')
AND A_RECID < '(lastPost)'
)
SELECT TOP 50 * FROM PreviousPosts
ORDER BY A_RECID ASC
其中“(变量)”和“(lastPost)”实际上用我的C#填充了正确的参数
我不再收到错误,但现在无论作为lastPost提供什么,我都会得到相同的结果。
更新:结果是表格中第一个有第一个名字的50个(在我的测试用例中)“詹姆斯”
感谢任何帮助:)
答案 0 :(得分:4)
您错过了CTE中的表名。见**[TABLENAME]**
WITH PreviousPosts AS
(
SELECT *
FROM [database].[dbo].**[TABLENAME]**
WHERE (A_1STNAME LIKE (variable)%)
AND A_RECID < (lastPost)
ORDER BY A_RECID DESC
)
SELECT TOP 50 * FROM PreviousPosts
ORDER BY A_RECID ASC
答案 1 :(得分:2)
如前所述,您错过了CTE中的表名。您还想知道您想从CTE中选择哪些列。
你应该改变:
SELECT TOP 50 FROM PreviousPosts ORDER BY A_RECID ASC
为:
SELECT TOP 50 * FROM PreviousPosts ORDER BY A_RECID ASC
答案 2 :(得分:0)
要添加到列表中,您无法在CTE中进行订购。为了得到你想要的东西,完全抛弃CTE:
SELECT top 50 *
FROM [database].[dbo].**[TABLENAME]**
WHERE (A_1STNAME LIKE (variable)%)
AND A_RECID < (lastPost)
ORDER BY A_RECID DESC
答案 3 :(得分:0)
这是一次尝试,我现在知道你的架构了。我仍然需要做出比我更舒服的假设,所以这可能不是正确的:
;WITH RankedRecords AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY A_RECID DESC) Row
, A_RECID
FROM [database]..[table]
WHERE A_1STNAME LIKE '(variable)%')
AND CAST(LEFT(A_RECID, 8) AS DATE) < CAST(LEFT('(lastPost)', 8) AS DATE)
)
SELECT TOP 50
T.*
FROM[database]..[table] T
INNER JOIN RankedRecords
ON RankedRecords.A_RECID = T.A_RECID
AND RankedRecords BETWEEN (@LastPost - 51) AND (@LastPost - 1)
ORDER BY RankedRecords.Row