這裏是我的出發點:如何將分頁/限制寫入2008 R2的SQL查詢?
SELECT * FROM crm_main t1
INNER JOIN crm_group_relationships t2
ON t1.id = t2.customerid
OUTER APPLY (
SELECT TOP 1 t3.timestamp, t3.customerid, t3.comments
FROM crm_comments t3
WHERE t1.id = t3.customerid
ORDER BY t3.timestamp ASC
) t3
WHERE t1.dealerid = '9999' AND t2.groupid = '251'
我不明白爲什麼微軟提出這個這麼難艾芬。在MySQL中,您可以使用帶偏移量的LIMIT子句。
基本上我想要做的是加入3個表,其中一個有拉只有一行(最新的評論是通過對記錄的最後意見的最新時間戳能夠排序)。我能夠實現這一點,但現在我堅持試圖將分頁寫入查詢。
我使用SQL 2008 R2。
我已經看過這個: http://blog.sqlauthority.com/2013/04/14/sql-server-tricks-for-row-offset-and-paging-in-various-versions-of-sql-server/,但我無法把我的想法圍繞這是如何工作的。
下面是基於上面的鏈接我的嘗試:
DECLARE @RowsPerPage INT = 10
DECLARE @PageNumber INT = 6
SELECT * FROM (
SELECT *,ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM crm_main t1
INNER JOIN crm_group_relationships t2
ON t1.id = t2.customerid
OUTER APPLY (
SELECT TOP 1 t3.timestamp, t3.customerid, t3.comments
FROM crm_comments t3
WHERE t1.id = t3.customerid
ORDER BY t3.timestamp ASC
) t3
WHERE t1.dealerid = '9999' AND t2.groupid = '251'
) AS SOD
WHERE SOD.RowNum BETWEEN ((@PageNumber - 1) * @RowsPerPage) + 1
AND @RowsPerPage * (@PageNumber)
輸出:
Msg 209, Level 16, State 1, Line 5
Ambiguous column name 'id'.
Msg 8156, Level 16, State 1, Line 16
The column 'id' was specified multiple times for 'SOD'.
嘗試將其更改爲'選擇T1 *,ROW_NUMBER()...'擺脫曖昧列錯誤。和'(ORDER BY t1.id)' – arserbin3
你試過'LEFT JOIN crm_comments t3 ON t3.timestamp =(從crm_comments中選擇max(timestamp),其中t1.id = customerid)' – stripthesoul
你定義'SOD'的方式是使用'SELECT * FROM sometable JOIN anothertable'。問題是'SELECT *',那裏有多個'id'列。你需要使用'SELECT <列出你需要的列>' – Lamak