SQL from 语句中的 IF 子句
我需要一个临时解决方案来解决我造成的问题。本质上我想计算两个值,但根据条件的结果使用不同的方法。
select userReturnval, userregisterid, OtherValue
FROM
(
(SELECT otherValue
FROM...
) as tblO --unrelated table
,
(
if (select count(userregisterid) from table1 where site =@siteID and userid=@userID) >0
SELECT userReturnval, userregisterid
FROM
(
SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY ...) as RANK
FROM ...
WHERE --first where clause
) as tblRank
WHERE (RANK =1)
else
SELECT userReturnval, userregisterid
FROM
(
SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY ...) as RANK
FROM ...
WHERE --different where clause
) as tblRank
WHERE (RANK =1)
) as tblR
我的 if 本身工作得很好,我只是为了让它作为更大查询的一部分工作。目前,sqlserver 不喜欢 if 存在其中。
希望有人能指出我正确的方向!
I need a temporary solution to a problem I've created. Essentially I want to calculate two values, but use a different method dependant on the result of a condition.
select userReturnval, userregisterid, OtherValue
FROM
(
(SELECT otherValue
FROM...
) as tblO --unrelated table
,
(
if (select count(userregisterid) from table1 where site =@siteID and userid=@userID) >0
SELECT userReturnval, userregisterid
FROM
(
SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY ...) as RANK
FROM ...
WHERE --first where clause
) as tblRank
WHERE (RANK =1)
else
SELECT userReturnval, userregisterid
FROM
(
SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY ...) as RANK
FROM ...
WHERE --different where clause
) as tblRank
WHERE (RANK =1)
) as tblR
My if works fine on its own, I just to get it working as part of the larger query. At the moment, sqlserver doesn't like the if being in there.
Hopefully someone can point me in the right direction!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试在 WHERE 子句中使用 case 语句,类似于下面的语句。请注意,我认为这对于性能来说并不是特别理想。
这样做确实可以让您将其保留为单个语句:
You can try using case statements in the WHERE clause, something like the statement below. Note that I don't think this will be particularly optimal for performance.
Doing it like this does allow you to keep it to a single statement though: