返回行的SQL查询除以日期

时间:2014-03-07 11:05:08

标签: mysql sql

我有这样的查询:

SELECT *, 
SUM(money_deposit + bonus_deposit) as money_deposit_total,
SUM(money_withdraw + bonus_withdraw) as money_withdraw_total
FROM transactions 
where player_id = 1 and created_date between '2013-01-01' and '2014-01-05' 
group by game_id;

我想要做的是按日期返回结果,因此我不想只返回1行,而是希望每个日期返回1行。

有什么建议吗?

4 个答案:

答案 0 :(得分:3)

您只需添加此

即可
group by game_DATE;

在SQL查询结束时

答案 1 :(得分:1)

试试这个

SELECT * FROM
   (
      SELECT game_id,created_date,
      SUM(money_deposit + bonus_deposit) as money_deposit_total,
      SUM(money_withdraw + bonus_withdraw) as money_withdraw_total
      FROM transactions 
      where player_id = 1 and created_date between '2013-01-01' and '2014-01-05' 
      group by game_id,game_DATE;
    ) AS T INNER JOIN transactions S ON S.game_id = T.game_id

答案 2 :(得分:1)

请按功能分组列出日期列。

SELECT *, 
SUM(money_deposit + bonus_deposit) as money_deposit_total,
SUM(money_withdraw + bonus_withdraw) as money_withdraw_total
FROM transactions 
where player_id = 1 and created_date between '2013-01-01' and '2014-01-05' 
group by game_id,created_date;

答案 3 :(得分:0)

如果删除*,则很容易。如果没有聚合函数,则无法显示未在组中使用的事务字段。一个常见的技巧是使用MAX函数,如果你知道给定日期和game_id的所有值都相同。

SELECT created_date
       ,game_id
       ,SUM(money_deposit + bonus_deposit) as money_deposit_total
       ,SUM(money_withdraw + bonus_withdraw) as money_withdraw_total
       ,Max( field_1) as field1
       ,Max( field_2) as field1
FROM transactions 
where player_id = 1 and created_date between '2013-01-01' and '2014-01-05' 
group by game_id,
         created_date 

另一种方法是在select

中使用子查询
SELECT created_date
       ,( Select game_name from game g where g.game_id = t.game_id) as name
       ,SUM(money_deposit + bonus_deposit) as money_deposit_total
       ,SUM(money_withdraw + bonus_withdraw) as money_withdraw_total

[...]或之后加入

   SELECT *
      FROM ( SELECT created_date
           ,game_id
           ,SUM(money_deposit + bonus_deposit) as money_deposit_total
           ,SUM(money_withdraw + bonus_withdraw) as money_withdraw_total
           ,Max( field_1) as field1
           ,Max( field_2) as field1
    FROM transactions 
    where player_id = 1 and created_date between '2013-01-01' and '2014-01-05' 
    group by game_id,
             created_date ) AUX
  JOIN game g ON g.gami_id = AUX.game_id