我有一个sql视图,其中包含来自3个链接实体(Title> Edition> SKU)的数据。此视图中的数据用于搜索3个实体中的任何字段。例如,如果指定条件title.regionid ='14',则视图将返回4,000个唯一行(每个SKU 1个),这些行属于765个唯一版本,属于456个唯一标题。
我需要的是使用Row_Number()启用基于标题的分页。所以
SELECT * FROM myview WHERE title.regionid = '14' AND Row BETWEEN 0 AND 35
问题是我的Row列需要按标题而不是按SKU计算行数,因此从4,000行的结果集中,如果第一个标题包含12个版本和65个SKU,则所有65行的行号应该是1,因为它们属于同一个标题。
我无法使用GroupBy,因为我的视图包含40多个列,所有这些列都可以通过WHERE子句进行搜索。
以下是查询:
SELECT *
FROM (
SELECT row_number() OVER (ORDER BY a.TitleSort ASC) AS Row, a.*
FROM (SELECT * FROM v_AdvancedSearch
WHERE
istitledeleted = 0
--AND ISBN = '1-4157-5842-5'
--AND etc
) AS a
) d
WHERE
Row BETWEEN 0 AND 35
在第一页中有35行只属于4个标题,但是Row列按行计数,所以它停在那里,而如果按标题计算,我会得到387行第1页......我怎么能在这种情况下完成分页?
答案 0 :(得分:0)
WITH Titles AS
(
SELECT *
FROM (
SELECT row_number() OVER (ORDER BY a.TitleSort ASC) AS Row, a.*
FROM (SELECT DISTINCT TitleSORT, TitleId FROM v_AdvancedSearch
WHERE
istitledeleted = 0
--AND ISBN = '1-4157-5842-5'
--AND PictureFormat = 'Widescreen'
--AND UPC = '0-9736-14381-6-0'
--AND Edition = 'Standard'
) AS a
) d
WHERE
Row BETWEEN 0 AND 35
)
SELECT * FROM v_AdvancedSearch V
INNER JOIN Titles ON Titles.TitleId = V.TitleId
WHERE istitledeleted = 0
--CONDITIONS NEED TO BE REPEATED HERE
--AND ISBN = '1-4157-5842-5'
ORDER BY V.TitleSort ASC
答案 1 :(得分:0)
此表格最适合我
WITH
[cte] AS (
SELECT
DENSE_RANK ( ) OVER ( ORDER BY [v].[TitleSort], [v].[TitleId] ) AS [ordinal],
[v].[TitleSort],
[v].[TitleId]
--,
--field list,
--etc
FROM [v_AdvancedSearch] AS [v]
WHERE
[v].[istitledeleted] = 0
--AND
--additional conditions AND
--etc
)
SELECT
[v].[ordinal],
[v].[TitleSort],
[v].[TitleId]
--,
--field list,
--etc
FROM [cte] AS [v]
WHERE
[v].[ordinal] >= 0 AND
[v].[ordinal] <= 35
ORDER BY [v].[ordinal];
https://docs.microsoft.com/en-us/sql/t-sql/functions/dense-rank-transact-sql
https://www.google.com/search?q=%22sql+server%22+%22select+star%22