总和count()按日期和分组依据php

时间:2017-05-19 18:41:06

标签: php sql while-loop group-by sum

我在mysql表上有这个:

user    |    open    |    date   
--------------------------------- 
User1   |     1      | 2017-05-19 
User2   |     1      | 2017-05-19 
User3   |     1      | 2017-05-19 
User4   |     1      | 2017-05-19 
User1   |     3      | 2017-05-18 
User2   |     5      | 2017-05-18 
User4   |     20     | 2017-05-17 
User1   |     2      | 2017-05-17 
User2   |     7      | 2017-05-17

我在数据mysql中搜索结果:

open = 2017-05-19

open2 = 2017-05-18

open3 = 2017-05-17

user    |    open    |    open2   |    open3   
---------------------------------------------
User1   |     1      |      3     |      2    
User2   |     1      |      5     |      7   
User3   |     1      |      0     |      0   
User4   |     1      |      0     |      20

你有想法???

我有用户分组,但问题出现之后!!!

先谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

你可以在

时使用案例
  select user, 
      ifnull(case when date  = '2017-05-19' then open end , 0)as open, 
      ifnull(case when date  = '2017-05-18' then open end, 0) as open2, 
      ifnull(case when date  = '2017-05-17' then open end,0)  as open3, 
  from my_table 

答案 1 :(得分:0)

SELECT user,
SUM(IF(date='2017-05-19',open,0)) AS open1,
SUM(IF(date='2017-05-18',open,0)) AS open2,
SUM(IF(date='2017-05-17',open,0)) AS open3
FROM SomeTableName
GROUP BY user;