如何使用Group By和Together在一起

时间:2012-04-02 13:22:12

标签: mysql ruby ruby-on-rails-3

我有以下数据集

id  name   units  release_date
1   salil   1    2012-04-02
2   salil   2    2012-03-21
3   salil   3    2012-04-02
4   salil   4    2012-03-02
5   salil   5    2012-04-02
6   xyz     1    2012-04-01
7   xyz     2    2012-03-30
8   xyz     3    2012-03-30
9   xyz     4    2012-04-01

我希望单位的SUM为每个名称的最大日期。像下面这样的东西

name  units     Max(release_date)
salil  9          2012-04-02
xyz    5          2012-04-01

我尝试跟随,但它无效

SELECT name, MAX(release_date) as date, sum(units) as units FROM reports

 GROUP BY name;

1 个答案:

答案 0 :(得分:0)

尝试以下:

    SELECT name, sum(units) as units 
    FROM reports as r
    LEFT JOIN (select max(date) as maxdate from reports group by name ) as mr
    ON r.date=mr.maxdate
    WHERE artist_name='Pacer1'  GROUP BY name;