使用Group By Clause进行求和

时间:2012-10-05 11:36:01

标签: mysql sql

我有这个问题..

SELECT DATE_FORMAT(utcdt,GET_FORMAT(DATE,'ISO')) as utcdt, 
                HOUR(utcdt) as hour, 
                country,
                sum(impressions) as impressions 
                FROM rtb_impressions where campaign_id='cid2204184260'
                GROUP BY utcdt, hour, country

这些是结果......

{'impressions': Decimal('1'), 'country': 'US', 'hour': 10L, 'utcdt': '2012-10-01'}
{'impressions': Decimal('40000'), 'country': 'US', 'hour': 9L, 'utcdt': '2012-10-02'}
{'impressions': Decimal('20000'), 'country': 'US', 'hour': 9L, 'utcdt': '2012-10-02'}

为什么我应该得到3行?应该总结012-10-02。

由于

2 个答案:

答案 0 :(得分:2)

你得到的是因为你正在按错误的值进行分组。 试试这个:

SELECT DATE_FORMAT(utcdt,GET_FORMAT(DATE,'ISO')) as utcdt, 
            HOUR(utcdt) as hour, 
            country,
            sum(impressions) as impressions 
            FROM rtb_impressions where campaign_id='cid2204184260'
            GROUP BY DATE_FORMAT(utcdt,GET_FORMAT(DATE,'ISO')), hour, country

答案 1 :(得分:1)

请改为尝试:

SELECT DATE_FORMAT(utcdt,GET_FORMAT(DATE,'ISO')) as utcdt, 
       HOUR(utcdt) as hour, 
       country,
       sum(impressions) as impressions 
FROM rtb_impressions
WHERE campaign_id='cid2204184260'
GROUP BY DATE_FORMAT(utcdt,GET_FORMAT(DATE,'ISO')), hour, country

如果要对格式化值进行分组,则需要确保在GROUP BY子句中应用相同的格式。