gpt4 book ai didi

SQL 动态 ORDER BY 使用别名

转载 作者:行者123 更新时间:2023-12-03 16:28:25 24 4
gpt4 key购买 nike

使用 SQL Server,我可以使用别名来订购普通的 SELECT 查询:

SELECT   
u.FirstName + ' ' + u.LastName as PhysicianName, COUNT(r.Id) as ReferralsCount
FROM
Referrals r
INNER JOIN
Users u ON r.PhysicianId = u.Id
GROUP BY
r.PhysicianId, u.FirstName, u.LastName
ORDER BY
PhysicianName

但是,尝试使用动态 ORDER BY 做同样的事情:

SELECT   
u.FirstName + ' ' + u.LastName as PhysicianName, COUNT(r.Id) as ReferralsCount
FROM
Referrals r
INNER JOIN
Users u ON r.PhysicianId = u.Id
GROUP
BY r.PhysicianId, u.FirstName, u.LastName
ORDER BY
CASE WHEN @orderby = 'PhysicianName' THEN PhysicianName END,
CASE WHEN @orderby = 'ReferralsCount' THEN ReferralsCount END

产生以下错误:

Msg 207, Level 16, State 1, Line 10
Invalid column name 'PhysicianName'.
Msg 207, Level 16, State 1, Line 11 Invalid column name 'ReferralsCount'.

最佳答案

SELECT 中定义的列别名只能在ORDER BY 中单独使用。不是在表达。

您可以按如下方式调整您的原始尝试。

;WITH T
AS (SELECT u.FirstName + ' ' + u.LastName AS PhysicianName,
COUNT(r.Id) AS ReferralsCount
FROM Referrals r
INNER JOIN Users u
ON r.PhysicianId = u.Id
GROUP BY r.PhysicianId,
u.FirstName,
u.LastName)
SELECT *
FROM T
ORDER BY CASE
WHEN @orderby = 'PhysicianName' THEN PhysicianName
END,
CASE
WHEN @orderby = 'ReferralsCount' THEN ReferralsCount
END

关于SQL 动态 ORDER BY 使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18105354/

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