按“状态”和“用户”字段分组

时间:2019-01-11 13:07:19

标签: mysql sql group-by

我有像这样的表结构

library(fuzzyjoin) library(tidyverse) # create a key/val tibble d1 <- tibble(key = c("stomach:biopsy", "colon:biopsy", "oesophagus:biopsy"), val = 1:3) # loop through the list elements having at least one element # left join with the key/val dataset # pull the column of 'val' # update the list elements tryout[i1] <- map(tryout[i1], ~ tibble(key = .x) %>% regex_left_join(d1) %>% pull(val))

users(user_id, username);

其中feedback(id, customer_id, user_id, status)将是status

我想要类似的结果

['scheduled', 'failed', 'cancelled']

我尝试了很多,但是未能通过| Username | scheduled count | failed count | cancelled count | |---------- |----------------- |-------------- |----------------- | | Sarah | 10 | 5 | 2 | | Alex | 8 | 7 | 5 | 子句获得结果。 它根据用户名而不是状态给出结果。

我尝试了一些查询

group by
sql> select users.username, count(*) as cal
from feedback
join users on users.user_id = feedback.user_id
group by feedback.user_id, feedback.status

2 个答案:

答案 0 :(得分:3)

您可以进行聚合:

select u.username,
       sum(status = 'scheduled') as scheduled_count,
       sum(status = 'failed') as failed_count ,
       sum(status = 'cancelled') as cancelled_count 
from user u inner join
     feedback f
     on f.user_id = u.user_id
group by u.username;

答案 1 :(得分:1)

我将使用条件聚合。 MySQL具有以下方便的快捷方式:

select u.username,
       sum(status = 'scheduled') as scheduled_count,
       sum(status = 'failed') as failed_count ,
       sum(status = 'cancelled') as cancelled_count 
from user u inner join
     feedback f
     on f.user_id = u.user_id
group by u.username;