Get top most N record from each group

Posted: May 9, 2012 in MySql
CREATE TABLE IF NOT EXISTS `tbl_post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_id` int(11) NOT NULL,
  `subject` varchar(255) NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

INSERT INTO `tbl_post` (`post_id`, `category_id`, `subject`) VALUES
(1, 1, 'world '),
(2, 2, 'Hello'),
(3, 1, 'Hi Kitty'),
(4, 2, 'google INc'),
(5, 1, 'Bollywood'),
(6, 3, 'Computer'),
(7, 3, 'PHP'),
(8, 2, 'jQuery'),
(9, 1, 'Radio'),
(10, 2, 'TV'),
(11, 3, 'Jeanse'),
(12, 2, 'mysql');

-- get top most 3 post from each category

SELECT post1.*
FROM tbl_post post1
LEFT OUTER JOIN tbl_post post2 ON ( post1.category_id = post2.category_id AND post1.post_id < post2.post_id )
GROUP BY post1.post_id
HAVING COUNT(*) < 2
ORDER BY category_id, post_id DESC

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s