查询在12个月内获得TOP 3行

时间:2015-08-04 09:13:38

标签: mysql group-by sql-order-by

我目前正在使用MySQL作为我的数据库。 对于所有TOP 3,我想检索COUNT最多TOPICS与最常见的12 months. 所以,我的结果通常会给我36 rows(1月的TOP 3,2月的TOP ......等等)

发布表格

CREATE TABLE IF NOT EXISTS `Post` (
  `post_id` VARCHAR(16) NOT NULL,
  `staff_id` INT NOT NULL,
  `topic_id` INT NOT NULL,
  `status_id` INT NOT NULL,
  `post_title` VARCHAR(100) NOT NULL,
  `post_date_time` DATETIME NOT NULL,
  `description` VARCHAR(1000) NOT NULL,
  `latest_update` DATETIME NULL,
  `approval` INT NULL,
  `approval_date` DATE NULL,
  PRIMARY KEY (`post_id`),
  INDEX `fk_Post_Staff(User)1_idx` (`staff_id` ASC),
  INDEX `fk_Post_Topic1_idx` (`topic_id` ASC),
  INDEX `fk_Post_Status1_idx` (`status_id` ASC),
  CONSTRAINT `fk_Post_Staff(User)1`
    FOREIGN KEY (`staff_id`)
    REFERENCES `staff` (`staff_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Post_Topic1`
    FOREIGN KEY (`topic_id`)
    REFERENCES `Topic` (`topic_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Post_Status1`
    FOREIGN KEY (`status_id`)
    REFERENCES `Status` (`status_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

1 个答案:

答案 0 :(得分:0)

select floor(period/100) `year`, period%100 `month`, topic_id 
   from 
     (select @n := if(@m=period, @n:=@n+1, @n:=1) n, @m:=period period, topic_id
        from 
          (select year(post_date_time)*100+month(post_date_time) period,
                  topic_id, count(post_id) count 
             from post 
           group by period, topic_id 
           order by period, count desc) t1, 
          (select @n:=1) tn, 
          (select @m:=0) tm ) t2 
   where n<4

Demo for simplified data

您可以通过写入尾部来设置数据的周期,例如

having `year` = 2015 and `month` between 1 and 6