1

I have a table with rows/data in the following structure

-----------
| SURVEY_ID |
------------
|  1       |
|  2       |
|  2       |
|  3       |
|  4       |
-----------

I want to get the distinct IDs and the maximum id in the same query. I tried

select distinct(survey_id) as survey_id , max(survey_id) as current 
from survey_main 
group by survey_id

This doesn't seem to return the correct result. What am I missing?

Edit: Required result

        ----------------------
        | Distinct|  Max     |
        ----------------------
        |  1       |  4      |
        |  2       |  4      |
        |  3       |  4      |
        |  4       |  4      |
        ----------------------
What have you tried
  • 10,650
  • 4
  • 30
  • 45
Vaishak Suresh
  • 5,535
  • 9
  • 39
  • 64

3 Answers3

4

I think Itay Moav-Malimovka's solution is just perfect, however if you really want to have two columns you could use ....

select distinct(survey_id) as identifier, 
       (select max(survey_id) from survey) as "current" 
  from survey_main;

Cheers!

Trinimon
  • 13,620
  • 9
  • 42
  • 60
3

If you are after the count of all survey_ids and the max in one query, try this:

select count(distinct survey_id) as number_of_survey_ids 
     , max(survey_id) as current 
from survey_main

And if you want to add the max value to every row and your database supports window functions, try this:

select survey_id 
     , max(survey_id) over () as current 
from survey_main
BellevueBob
  • 9,310
  • 5
  • 28
  • 53
2
SELECT DISTINCT *
FROM T
ORDER BY SURVEY_ID DESC

The first result is the MAX, the entire Dataset is the distinct

Itay Moav -Malimovka
  • 50,983
  • 60
  • 187
  • 270