I need to get maximum and minimum values but also I need to get row id of these maximum or minimum on the same row.
SELECT MIN([Value]), MAX([Value]), id
FROM [AnalystEstimates].[dbo].[AnalystEstimateValues]
GROUP BY indicatorid
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s very unclear what you want from your question. Do you really want the GROUP BY indicatorid? If not then it’s quite simple and you already have many answers. But if you do want to GROUP BY then it’s more difficult and no-one has got it quite right yet. I also assume that you only want one row per indicatorid, and if there are duplicate rows that have the same max/min then it’s better to just choose one of them arbitrarily instead of returning both.
Here’s my attempt, using CTEs (requires SQL Server 2005 or newer):
Here is some data I used to test it:
And here’s the output I get:
If this isn’t what you want, can you please try to improve your question to tell us what you do want?
Update: Here’s an alternative solution based on Craig Young’s answer but using joins instead of subselects:
This is cleaner and probably also faster than my first version, although I haven’t run performance tests to verify this.