单个语句上的多个计数列按不同的用户名分组

时间:2016-08-20 09:26:41

标签: mysql sql

相当新的SQL并且在特定声明中遇到一些麻烦。

以下是一些示例数据:

date       | username
2016-01-01 | JIM
2016-01-01 | BOB
2016-01-01 | BOB
2016-01-02 | JIM
2016-01-03 | JIM
2016-01-03 | JIM
2016-01-03 | BOB

我想要做的是计算每个用户名的每个不同日期,除了我希望每个日期在自己的列上,每个用户名的每个日期都有个人计数。

我将通过PHP提供每个日期,并希望您可以在单个SQL查询中返回以下表:

username | 2016-01-01 | 2016-01-02 | 2016-01-03
JIM      | 1          | 1          | 2
BOB      | 2          | 0          | 1

到目前为止,我所能达到的只是日期,用户名和每用户每天的计数列表:

SELECT date,
       haulier,
       count(*)
FROM demo
WHERE date >= '2016-01-01' AND
      date <= '2016-01-03'
GROUP BY date,
         haulier

此致

2 个答案:

答案 0 :(得分:0)

以下是我使用pivot提出的建议。

drop view IF EXISTS username_count;

create view username_count as (
  select
    username,
    case when date = "2016-01-01" then username end as monday,
    case when date = "2016-01-02" then username end as tuesday,
    case when date = "2016-01-03" then username end as wednesday,
    case when date = "2016-01-04" then username end as thursday,
    case when date = "2016-01-05" then username end as friday
  from table_name
);

drop view IF EXISTS username_count_pivot;

create view username_count_pivot as (
  select
    username,
    count(monday) as monday,
    count(tuesday) as tuesday,
    count(wednesday) as wednesday,
    count(thursday) as thursday,
    count(friday) as friday
  from username_count
  group by username
);

select * from username_count_pivot;

返回下表:

username | monday | tuesday | wednesday | thursday | friday
JIM      | 1      | 1       | 2         | 0        | 0
BOB      | 2      | 0       | 1         | 0        | 0

答案 1 :(得分:0)

您可以使用条件聚合:

select s.username,
       sum(date = '2016-01-01') as cnt_20060101,
       sum(date = '2016-01-02') as cnt_20060102,
       sum(date = '2016-01-03') as cnt_20060103
from sample s
group by s.username;

如果您不知道具体日期,则需要使用动态SQL。您可以通过Google“MySQL动态数据透视”查看如何执行此操作的示例。