2

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
  • 11,018
  • 4
  • 31
  • 45
Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66

3 Answers3

8

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,839
  • 9
  • 44
  • 60
4

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,498
  • 5
  • 29
  • 56
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
  • 52,579
  • 61
  • 190
  • 278