id serviceid name cost date
201 15 X 50 25.12.2016
201 15 Y 55 29.11.2016
201 120 Z 50 27.11.2016
201 19 w 50 22 .11.2016
201 158 p 50 23.11.2016
201 18 q 50 21.11.2016
201 16 rs 50 24.11.2016
201 81 rs 50 2.11.2016
202 18 X 50 25.12.2016
202 18 Y 55 29.11.2016
202 15 Z 50 27.11.2016
202 19 w 50 22 .11.2016
203 15 p 50 23.11.2016
203 18 q 50 21.11.2016
203 16 rs 50 24.11.2016
0 81 rs 50 2.11.2016
Desire Output :
id serviceid name cost date
201 15 X 50 25.12.2016
201 15 Y 55 29.11.2016
201 120 Z 50 27.11.2016
201 16 rs 50 24.11.2016
202 18 X 50 25.12.2016
202 18 Y 55 29.11.2016
202 15 Z 50 27.11.2016
202 19 w 50 22 .11.2016
203 15 p 50 23.11.2016
203 18 q 50 21.11.2016
203 16 rs 50 24.11.2016
0 81 rs 50 2.11.2016
i want to display each record 4 - 4 record service for each id i am trying to apply using self Join but there is Problem coming please tell or suggest me how to ac-chive for this.
SELECT a.*
FROM mytable AS a
WHERE
(SELECT COUNT(*) FROM mytable AS b
WHERE b.id = a.id and b.serviceid >= a.serviceid) <= 4
ORDER BY a.id , a.date
this query am trying but i am unable to fetch it for each id there should top 4 service id based on date.