gpt4 book ai didi

tsql - 用于分页的公用表中的 T-SQL 动态排序依据

转载 作者:行者123 更新时间:2023-12-04 22:50:54 25 4
gpt4 key购买 nike

我找到了一些用于动态排序和顺序的很棒的 sql 代码,但我想知道是否有人可以帮助我重新调整它,以便下面的 PROC 中的 CTE 使用动态排序/顺序。此代码运行 - 但输出不是我所追求的,因为 ORDER BY p.ProductId 首先在 CTE 中发生,然后 ORDER BY CASE 语句仅适用于记录 6 到 10

DECLARE @Skip int
DECLARE @Take int
DECLARE @OrderBy VARCHAR(50)

SET @Skip = 5;
SET @Take = 5;
SET @OrderBy = 'PriceAsc';


WITH ProductCT AS
(
SELECT ROW_NUMBER() OVER(ORDER BY p.ProductId) AS RowNum
, p.ProductId
FROM dbo.Product AS p
)
SELECT p.ProductId
,p.Title
,p.Price
FROM dbo.Product AS p
INNER JOIN ProductCT AS pct ON pct.ProductId = p.ProductId
WHERE pct.RowNum BETWEEN @Skip + 1 AND (@Skip + @Take)
ORDER BY
CASE
WHEN @OrderBy = 'TitleAsc' THEN (RANK() OVER (ORDER BY p.Title))
WHEN @OrderBy = 'TitleDesc' THEN (RANK() OVER (ORDER BY p.Title DESC))
WHEN @OrderBy = 'PriceAsc' THEN (RANK() OVER (ORDER BY p.Price))
WHEN @OrderBy = 'PriceDesc' THEN (RANK() OVER (ORDER BY p.Price DESC))
ELSE (RANK() OVER (ORDER BY p.Price))
END

在此先感谢您的任何建议 :-)

最佳答案

我最初将@Johan 的答案标记为正确,因为它有效,但我有点不确定 INNER JOIN 以及此查询的整体复杂性。

我和我的一位同事聊了聊这个问题,他想出了这个非常整洁的解决方案(感谢汤姆!!)所以我想我会分享它:

DECLARE @Skip int
DECLARE @Take int
DECLARE @OrderBy VARCHAR(50)

SET @Skip = 5;
SET @Take = 5;
SET @OrderBy = 'PriceAsc';


WITH ProductCT AS
(
SELECT
CASE
WHEN @OrderBy = 'TitleAsc' THEN ROW_NUMBER() OVER (ORDER BY p.Title)
WHEN @OrderBy = 'TitleDesc' THEN ROW_NUMBER() OVER (ORDER BY p.Title DESC)
WHEN @OrderBy = 'PriceAsc' THEN ROW_NUMBER() OVER (ORDER BY p.Price)
WHEN @OrderBy = 'PriceDesc' THEN ROW_NUMBER() OVER (ORDER BY p.Price DESC)
END AS RowNum
, p.ProductId
FROM dbo.Product AS p
)
SELECT p.ProductId
,p.Title
,p.Price
FROM dbo.Product AS p
INNER JOIN ProductCT AS pct ON pct.ProductId = p.ProductId
WHERE pct.RowNum BETWEEN @Skip + 1 AND (@Skip + @Take)
ORDER BY RowNum

关于tsql - 用于分页的公用表中的 T-SQL 动态排序依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5948996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com