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
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
Your query would return the max/min for each ID as you are grouping by the ID. Try something like this
This might do it, though I don't have mssql so I can't test it. Especially the square brackets may need tweaking. Other than that it should be fairly standard sql and does what you want.
It gets all min (id/value) and max (id/value) grouped by indicatorid. In the same row.
If Min = Max, you'll the get same IDs (there may be tied Min and Max values)
If not, there is/are ID(s) per min/max value.
You can have 2 rows or 4 columns, basically.
Edit:
The TOP solutions won't give you rows where you have tied MIN/MAX values unless defined WITH TIES
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.
Important question
Mark Byers' sample data shows a scenario that you need to contemplate:
So which of the two id's should be displayed?
I have assumed it sufficient to display the lowest id. The following query should be the most efficient, and would benefit from an index on (indicatorid, Value).