按类型对列进行分组

时间:2017-06-13 13:20:05

标签: mysql sql group-by

我有一个像这样的主表

+----------------------------------------------+
| id |  user_id  |   date     |  vehicle_type  |  
+----------------------------------------------+
| 1  |  1        | 2017-06-01 |       1        |
| 2  |  1        | 2017-06-01 |       2        |
| 3  |  1        | 2017-06-01 |       1        |
| 4  |  1        | 2017-06-02 |       2        |
| 5  |  1        | 2017-06-02 |       1        |
| 6  |  2        | 2017-06-01 |       2        |
| 7  |  2        | 2017-06-01 |       1        |
| 8  |  2        | 2017-06-01 |       2        |
| 9  |  2        | 2017-06-02 |       1        |
+----------------------------------------------+

我希望按user_iddate进行分组,并将vehicle_type相加取决于其值,并创建为视图。 这里我想要的输出

+------------------------------------------------+-------------------+
| id |  user_id  |   date     |  vehicle_type_1  |   vehicle_type_2  |
+------------------------------------------------+-------------------+
| 1  |  1        | 2017-06-01 |       2          |          2        |
| 4  |  1        | 2017-06-02 |       1          |          1        |
| 6  |  2        | 2017-06-01 |       1          |          2        |
| 9  |  2        | 2017-06-02 |       1          |          0        |
+------------------------------------------------+-------------------+

问题是获得输出的最佳sql(查询),就像我想要的那样。 谢谢,

3 个答案:

答案 0 :(得分:2)

SELECT user_id 
  ,date
  ,SUM(IIF(vehicle_type = 1,1,0)) as vehicle_type_1
  ,SUM(IIF(vehicle_type = 2,1,0)) as vehicle_type_2 
FROM yourtable
GROUP BY user_id, date  

我不明白为什么你需要输出中的id。如果真的需要,只需在select子句

中添加MIN(id)或MAX(id)

答案 1 :(得分:1)

您需要使用case语句来获取所需的输出。尝试以下

 select max(id) id,user_id,date,sum(case when vehicle_type=1 then 1 else 0 end) vehicle_type_1,sum(case when vehicle_type=2 then 1 else 0 end) vehicle_type_2  from urtable 
    group by user_id,date

答案 2 :(得分:0)

根据上述问题中提到的描述作为解决方案,请尝试执行以下SQL选择查询

    SELECT user_id, 
       date, 
       Count(id)        AS vehicle_type_1, 
       (SELECT Count(id) 
        FROM   mytbl 
        WHERE  vehicle_type = 2 
               AND user_id = tbl.user_id 
               AND date = tbl.date 
        GROUP  BY user_id, 
                  date) AS vehicle_type_2 
FROM   mytbl AS tbl 
WHERE  vehicle_type = 1 
GROUP  BY user_id, 
          date