具有聚合函数的MySQL GROUP BY DateTime

时间:2015-09-14 20:11:58

标签: mysql sql group-by aggregate

我似乎记得在Oracle中按预期工作,但我无法弄清楚如何在MySQL中正确使用它。

这是我的问题:

// This is pretending to be the data structure you are using
public class LongLat {
    private float mLongitude;
    private float mLatitude;

    // constructor from string for convenience
    public LongLat(string longLatString ) {
        string[] longLatParts = longLatString.Split(',');
        mLongitude = float.Parse(longLatParts[0]);
        mLatitude = float.Parse(longLatParts[1]);
    }

    public float Longitude {get; set; }
    public float Latitude {get; set; }
}

// The sorter
public class LongLatSort : IComparer {
    public int IComparer.Compare(object a, object b) {
        LongLat o1=(LongLat)a;
        LongLat o2=(LongLat)b;
        if (o1.Longitude > o2.Longitude) {
            return -1; // flipped for descending
        } else if ( o1.Latitude < o2.Longitude ) {
            return 1;  // flipped for descending
        }
        // secondary sort on latitude when values are equal
        return o1.Latitude > o2.Latitude ? -1 : 1; // flipped for descending
    }
}

// now you should be able to use the sorter something like this?
// though best to not instantiate the Comparer every time but you get the idea
// EDIT: create your array of LongLats from strings first
Arrays.Sort( yourArrayofLongLats, new LongLastSort() );

运行它会产生如下结果:

SELECT DateTimeStamp, MAX(Value) FROM t1
GROUP BY YEAR(DateTimeStamp), MONTH(DateTimeStamp), DAY(DateTimeStamp);

但我希望它看起来像这样,DateTimeStamps与值匹配:

DateTimeStamp       Value
2015-09-09 00:00:29 100
2015-09-10 00:00:05 58
2015-09-11 00:00:57 62
2015-09-12 00:00:49 69
2015-09-13 00:00:43 97

正在选择正确的最大值,但这些最大值的匹配DateTimeStamps不是。相反,它看起来像是每天选择的第一个DateTimeStamp值。如何更改查询以显示匹配的DateTimeStamps?

1 个答案:

答案 0 :(得分:0)

如果您只需要删除时间部分,则需要使用date功能:

SELECT date(DateTimeStamp) AS DateTimeStamp, MAX(Value) AS MaxValue
FROM t1
GROUP BY date(DateTimeStamp);

注意:当您选择它时,通过某种方式进行分组通常是有意义的。如果您需要的是每天的最大值,则无需按YEAR(DateTimeStamp), MONTH(DateTimeStamp), DAY(DateTimeStamp)进行分组。