取最后一行分组日期

时间:2019-04-02 17:44:02

标签: sql query-builder

我需要按日期选择内容统计信息组。

这里是记录示例:

id cid viewCount created_at
1    1  50        31-12-2018 18:00:00
2    1  50        01-01-2019 18:00:00
3    2  50        01-01-2019 18:00:00
4    2  100       01-01-2019 19:00:00
5    2  150       01-01-2019 20:00:00
6    3  1000      01-01-2019 15:00:00

需要返回:

id cid viewCount date
1    1  50        31-12-2018
2    1  50        01-01-2019
5    2  150       01-01-2019
6    3  1000      01-01-2019

我尝试了以下代码

        $qb = $this->createQueryBuilder('c');
        $qb->select('a.id as id')
           ->addSelect('COALESCE(SUM(a.viewCount),0) as viewCount')
           ->addSelect('DATE_FORMAT(a.createdAt, \'%d-%m-%Y\') as date');
           ->innerJoin('c.analytics', 'a')
           ->groupBy('c.cid')
           ->addGroupBy('date')
           ->orderBy('a.createdAt', 'ASC');

返回:

id cid viewCount date
1   1  50        31-12-2018
2   1  50        01-01-2019
3   2  50        01-01-2019
4   2  100       01-01-2019
5   2  150       01-01-2019
6   3  1000      01-01-2019

我试图创建一个子查询:

        $qbLastHour = $this->createQueryBuilder('cc');
        $qbLastHour->select('MAX(DATE_FORMAT(aa.createdAt, \'%H\'))')
            ->innerJoin('cc.analytics', 'aa')
            ->where('cc.id=c.id')
            ->groupBy('cc.cid')
            ->addGroupBy('s');

        $qb->addSelect(sprintf("(%s) AS r", $qbLastHour->getDQl()));

但是出了点问题,因为我没有在子查询中按日期分组。

如果有人可以帮助我。谢谢

1 个答案:

答案 0 :(得分:1)

更新

再次尝试在sql中,每个日期仅选择一行,并根据每天的最大时间选择cid

SELECT id, c.cid, viewCount, max_date
FROM content a
JOIN content_analytic c ON a.id = c.content_id
RIGHT JOIN (SELECT c.cid, DATE_FORMAT(created_at, '%d-%m-%Y') dt, MAX(created_at) max_date
            FROM content a
            JOIN content_analytic c ON a.id = c.content_id
            GROUP BY dt, c.cid) x ON x.max_date = a.created_at and x.cid = c.cid

这就是我认为查询应使用纯sql的方式

SELECT c.cid, COALESCE(SUM(a.viewCount), 0), DATEFORMAT(a.created_at, ‘%d-%m-%Y’) as date
FROM content a
INNER JOIN content_analytic c ON a.id = c.content_id
GROUP BY c.cid, date
ORDER BY date