按计数分组()

时间:2012-01-07 11:46:40

标签: mysql sql

我正在尝试进行以下查询:

SELECT
    DATE_FORMAT( date, '%Y %m' ) AS `Month`, 
    COUNT( schedule_id ) AS `Shifts`,
    COUNT(user_id) AS `Users`
FROM 
    schedule
GROUP BY 
    `Month`, `Shifts`

它应该给出一个频率表,说明每月有多少用户工作一定数量的班次(例如,在12月,有10个用户工作20班,12个用户工作15班等)。

但MySQL无法对COUNT()进行分组,因此查询会中断。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
    `Month`, `Shifts`, COUNT(`User`) `Users`
FROM (  
    SELECT -- select nr of shifts per user
        DATE_FORMAT( date, '%Y %m' ) AS `Month`, 
        user_id AS `User`,
        COUNT( schedule_id ) AS `Shifts`
    FROM 
        schedule
    GROUP BY 
        `Month`, `User`
) s
GROUP BY `Month`, `Shifts`

内部查询返回月份,用户和班次计数。在外部查询中,您可以按班次分组。

答案 1 :(得分:1)

使用子查询获取每个标识符的计数(示例中为列ID),然后将其与原始查询连接

SELECT ... FROM schedule sh JOIN ( SELECT id, COUNT( schedule_id ) AS Shifts FROM schedule ) AS cnt ON cnt.id = sh.id GROUP BY ..., cnt.Shifts

答案 2 :(得分:0)

SELECT
    y
  , m
  , Shifts
  , COUNT(*) AS Users 
FROM
  ( SELECT
        YEAR(date) AS y
      , MONTH(date) AS m
      , user_id 
      , COUNT(*) AS Shifts
    FROM 
        schedule
    GROUP BY 
        YEAR(date), MONTH(date), user_id 
  ) AS grp
GROUP BY
    y
  , m
  , Shifts