如何选择与其对应的最早日期和数据

时间:2012-05-16 16:41:56

标签: sql group-by

我有一个非常简单的问题就是踢我的屁股。

CUSTNMBR   |  first_date |  SOPNUMBE
----------------------------------------
3344771005 |  2012-05-03 |  334471961748         
3344771005 |  2012-04-04 |  334476873726

在上表中,我想返回最早的日期以及custnumbrsopnumbe所以它看起来像这样

3344771005 |  2012-04-04 |  334476873726

我用过这个

Select a.CUSTNMBR, min(a.Tax_Date) as first_date, a.SOPNUMBE
from SOP30200 as a
where a.CUSTNMBR = '3344771005'
Group by a.CUSTNMBR, a.SOPNUMBE

但是它会返回所有变量,如果我将组a.sopnumbe击倒,则会出错。

2 个答案:

答案 0 :(得分:2)

试试这个:

Select top 1 a.CUSTNMBR, a.Tax_Date as first_date, a.SOPNUMBE 
from SOP30200 as a 
where a.CUSTNMBR = '3344771005' 
order by a.Tax_Date asc

答案 1 :(得分:0)

尝试

Select TOP 1 a.CUSTNMBR, min(a.Tax_Date)as first_date, a.SOPNUMBE
from SOP30200 as a
where a.CUSTNMBR = '3344771005'
Group by a.CUSTNMBR, a.SOPNUMBE'
ORDER BY 2 ASC