2013-03-18 29 views
0

SELECT DISTINCT和MAX我有行/數據表結構如下在同一個查詢

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

我想獲得不同的ID,並在同一個查詢的最大ID。我試過

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

這似乎沒有返回正確的結果。我錯過了什麼?

編輯:所需的結果

 
     ---------------------- 
     | Distinct| Max  | 
     ---------------------- 
     | 1  | 4  | 
     | 2  | 4  | 
     | 3  | 4  | 
     | 4  | 4  | 
     ---------------------- 
+0

你有沒有試過這個http://stackoverflow.com/questions/612231/how-can-i-select-rows-with-maxcolumn-value-distinct-by-another-column-in-sql – Mowgli 2013-03-18 20:21:29

+0

你想要嗎?所有survey_ids的計數和最大值(兩列,一行)? – BellevueBob 2013-03-18 20:22:54

+0

@ ItayMoav-Malimovka我只是不想執行2個單獨的查詢爲次要的事情。每行重複的最大值對我來說都很好。 – 2013-03-18 20:25:03

回答

1

我覺得伊泰Moav-Malimovka的解決方案是恰到好處的,但是如果你真的想你可以使用兩列....

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

乾杯!

+0

這就是我想要的!謝謝您的幫助! – 2013-03-18 20:38:12

2
SELECT DISTINCT * 
FROM T 
ORDER BY SURVEY_ID DESC 

的第一個結果是MAX,整個數據集是不同

+0

真的不是我想要的。我希望查詢返回最大值,我可以手動解析結果集。 – 2013-03-18 20:31:55

0

如果大家都survey_ids的計數和一個查詢中的最大後,試試這個:

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

如果你想增加最大值到每一行你的數據庫支持窗口功能,試試這個:

select survey_id 
    , max(survey_id) over() as current 
from survey_main