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!
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: