2013-03-18 57 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