Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Select MAX with Case Else

Author  Topic 

velnias2010
Posting Yak Master

125 Posts

Posted - 2011-05-18 : 05:11:10
Hey I have the following query
SELECT MAX(stepId) AS maxId FROM tblUserQuestionnaireHistory WHERE (userId = @UserId) AND (programmeId = 25) AND (success = 1)

Now what I want to add is the following that if the maxStepId is 5 or greater than max is 4 otherwise select MAX(stepId)

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2011-05-18 : 05:38:38
SELECT
CASE WHEN MAX(stepId) >= 5 THEN 4
ELSE MAX(stepId)
END yourVal
FROM tblUserQuestionnaireHistory
WHERE ( userId = @UserId )
AND ( programmeId = 25 )
AND ( success = 1 )


--------------------------
http://connectsql.blogspot.com/
Go to Top of Page

velnias2010
Posting Yak Master

125 Posts

Posted - 2011-05-18 : 07:50:37
Thanks
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2011-05-18 : 09:21:50
Not sure what you're trying to accomplish...and I wasn't sure that would work...ir does



CREATE TABLE #myTable99(
stepId int
, userId varchar(20)
, programmeId int
, success int
)

INSERT INTO #myTable99(stepId, userId, programmeId, success)
SELECT 1, 'X002548' , 10, 1 UNION ALL
SELECT 6, 'XXX' , 25, 1 UNION ALL
SELECT 2, 'XXX' , 25, 1 UNION ALL
SELECT 3, 'ZZZ' , 25, 1 UNION ALL
SELECT 1, 'ZZZ' , 25, 1

DECLARE @UserID varchar(20);

SET @UserID = 'XXX'

SELECT CASE WHEN MAX(stepId) >= 5 THEN 4
ELSE MAX(stepId)
END yourVal
FROM #myTable99
WHERE userId = @UserId
AND programmeId = 25
AND success = 1

SET @UserID = 'ZZZ'

SELECT CASE WHEN MAX(stepId) >= 5 THEN 4
ELSE MAX(stepId)
END yourVal
FROM #myTable99
WHERE userId = @UserId
AND programmeId = 25
AND success = 1

DROP TABLE #myTable99
GO




Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page
   

- Advertisement -