在MySql中按第一个查询分组

时间:2014-01-22 18:15:02

标签: mysql

我需要将以下(访问中的sql)转换为mysql。它是第一个查询的组,但是obv mysql无法处理第一个或最后一个。

SELECT First([20121202].Date) AS FirstOfDate, First([20121202].Time) AS FirstOfTime, [20121202].HomeMatchingId, [20121202].AwayMatchingId, [20121202].RunningStatus
FROM 20121202
GROUP BY [20121202].HomeMatchingId, [20121202].AwayMatchingId, [20121202].RunningStatus
HAVING ((([20121202].RunningStatus)=1))

基本上我是在游戏(hometeam v awayteam)进场之后(runningstatus = 1)

提前致谢

2 个答案:

答案 0 :(得分:1)

不确定日期是什么,但是使用常规聚合呢?

SELECT 
    MIN(`Date`) AS `FirstOfDate`, 
    MIN(`Time`) AS `FirstOfTime`, 
    `HomeMatchingId`, 
    `AwayMatchingId`, 
    `RunningStatus`
FROM `20121202`
GROUP BY 
    `HomeMatchingId`, 
    `AwayMatchingId`, 
    `RunningStatus`
HAVING 
    `RunningStatus`=1

答案 1 :(得分:1)

我认为first的目的是获得最早的约会。如果每个日期最多有一行,那么您可以这样做:

SELECT t.Date AS FirstOfDate, t.Time AS FirstOfTime,
       t.HomeMatchingId, t.AwayMatchingId, t.RunningStatus
FROM `20121202` t join
      (select HomeMatchingId, AwayMatchingId, min(date) as mindate
       from `20121202`
       WHERE RunningStatus = 1;
       group by HomeMatchingId, AwayMatchingId
      ) tmin
      on t.date = tmin.date and t.HomeMatchingId = tmin.HomeMatchingId and
         tmin.AwayMatchingId and t.AwayMatchingId and
WHERE RunningStatus = 1;

我将RunningStatus上的条件移到where子句,因为这样更有效。