Home  >  Q&A  >  body text

mysql group by多个字段

SELECT 
    用户ID,
    FROM_UNIXTIME(时间戳,'%Y%m') month 
FROM 
    table 
GROUP BY 
    month,用户ID
以上语句想在table表中查询出用户ID和月份,然后使用月份和用户ID(表中同一个用户ID可能出现多次)进行分组,如何在SELECT后添加一个数量字段再按月份统计出用户的数量?
ringa_leeringa_lee2742 days ago891

reply all(5)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 15:09:43

    Can you please stop writing the problem in the code? . . Think about the user experience. . .

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:09:43

    Yes, group by can be followed by multiple fields, just separate them with commas.

    reply
    0
  • 黄舟

    黄舟2017-04-17 15:09:43

    Can I understand what the poster said (表中同一个用户ID可能出现多次) to mean that he wants to get the number of unique users per month?

    If so, the Sql statement would be like this

    SELECT COUNT(DISTINCT 用户ID) count,FROM_UNIXTIME(时间戳,'%Y%m') month FROM table GROUP BY month

    If not, that’s it

    SELECT COUNT(用户ID) count,FROM_UNIXTIME(时间戳,'%Y%m') month FROM table GROUP BY month

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:09:43

    Use the form count(xxxx) as xxxx_num

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:09:43

    It would be unrealistic to display all user IDs in a single column as requested by the poster.
    If the number of users is counted by month, it should be
    SELECT COUNT(DISTINCT user ID) count,FROM_UNIXTIME(timestamp,' %Y%m') month FROM table GROUP BY month

    reply
    0
  • Cancelreply