SQL查找最早的开始日期

时间:2013-09-15 12:41:02

标签: sql oracle

我已经坚持这么久了,我无法在网上找到/找到答案。

所以到目前为止我有这个代码:

select c.country_olympic_name, 
       max(sg_start) 
  from summergames a, 
       country c
 where a.country_isocode = c.country_isocode
 group by c.country_isocode
HAVING max(sg_start) = (select max(sg_start) 
                          from summergames 
                         group by country_isocode)
 order by c.country_isocode;

它需要做的是找出最早的比赛开始日期..

我得到了它的工作,但是一旦我将country_olympic_name添加到与sg_start不同的表中,它就会给我这个错误:

  

ORA-00979:不是GROUP BY表达式
  00979. 00000 - “不是GROUP BY表达式”

3 个答案:

答案 0 :(得分:1)

如果您只想使用最旧/最新的日期,请使用简单的聚合MIN(sg_date)。

但是如果你想要那个日期的所有列,你必须切换到OLAP函数:

SELECT *
FROM 
 (
   SELECT *,
      ROW_NUMBER()
      OVER (-- when you want the earliest date per country: PARTITION BY c.country_isocode
            ORDER BY sg_start) AS rn -- use DESC for newest date
   FROM summergames a, country c
   WHERE a.country_isocode = c.country_isocode
 ) dt 
WHERE rn = 1
ORDER BY c.country_isocode;

答案 1 :(得分:0)

这样做你想要的吗?

select c.country_olympic_name, min(sg_start) 
from summergames a join
     country c
    on a.country_isocode = c.country_isocode
group by c.country_olympic_name

答案 2 :(得分:0)

SELECT中聚合的任何字段也必须在GROUP BY中。否则,SQL引擎不知道如何按非聚合分组。您可以将SQL更改为以下内容:

select c.country_olympic_name, max(sg_start) 
  from summergames a, country c
 where a.country_isocode = c.country_isocode
 group by c.country_isocode, c.country_olympic_name
having max(sg_start) = ( select max(sg_start) 
                           from summergames 
                          group by country_isocode)
order by c.country_isocode;