Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- DROP TABLE IF EXISTS t_barang;
- CREATE TABLE t_barang(
- id INT AUTO_INCREMENT PRIMARY KEY,
- nama VARCHAR(50),
- kategori TINYINT,
- jml TINYINT,
- waktu DATE
- );
- INSERT INTO t_barang(nama,kategori,jml,waktu)
- VALUES
- ('sepatu bot anak',1,6,'2017-04-01'),
- ('baju anak perempuan',2,4,'2017-04-01'),
- ('sepatu olahraga',1,8,'2017-04-01'),
- ('baju anak laki-laki',2,4,'2017-04-02'),
- ('sepatu bot dewasa',1,6,'2017-04-02'),
- ('sepatu olahraga anak',1,2,'2017-04-02'),
- ('sepatu futsal',1,9,'2017-04-03'),
- ('sepatu tenis',1,3,'2017-04-04'),
- ('sepatu golf',1,2,'2017-04-04'),
- ('baju tidur anak',2,4,'2017-04-05'),
- ('baju olahraga anak',2,5,'2017-04-06');
- SELECT * FROM t_barang ORDER BY kategori,waktu DESC;
- +----+----------------------+----------+------+------------+
- | id | nama | kategori | jml | waktu |
- +----+----------------------+----------+------+------------+
- | 9 | sepatu golf | 1 | 2 | 2017-04-04 |
- | 8 | sepatu tenis | 1 | 3 | 2017-04-04 |
- | 7 | sepatu futsal | 1 | 9 | 2017-04-03 |
- | 6 | sepatu olahraga anak | 1 | 2 | 2017-04-02 |
- | 5 | sepatu bot dewasa | 1 | 6 | 2017-04-02 |
- | 1 | sepatu bot anak | 1 | 6 | 2017-04-01 |
- | 3 | sepatu olahraga | 1 | 8 | 2017-04-01 |
- | 11 | baju olahraga anak | 2 | 5 | 2017-04-06 |
- | 10 | baju tidur anak | 2 | 4 | 2017-04-05 |
- | 4 | baju anak laki-laki | 2 | 4 | 2017-04-02 |
- | 2 | baju anak perempuan | 2 | 4 | 2017-04-01 |
- +----+----------------------+----------+------+------------+
- SELECT a.nama,a.kategori, a.jml, DATE_FORMAT(a.waktu,'%d-%b-%Y') AS waktu
- FROM (
- SELECT
- *,
- IF( @prev <> kategori, @rownum := 1, @rownum := @rownum+1 ) AS rank,
- @prev := kategori
- FROM t_barang t
- JOIN (SELECT @rownum := NULL, @prev := 0) AS r
- ORDER BY t.kategori,t.waktu DESC
- ) AS a
- WHERE a.rank <= 3
- ORDER BY kategori, waktu DESC;
- +---------------------+----------+------+-------------+
- | nama | kategori | jml | waktu |
- +---------------------+----------+------+-------------+
- | sepatu tenis | 1 | 3 | 04-Apr-2017 |
- | sepatu golf | 1 | 2 | 04-Apr-2017 |
- | sepatu futsal | 1 | 9 | 03-Apr-2017 |
- | baju olahraga anak | 2 | 5 | 06-Apr-2017 |
- | baju tidur anak | 2 | 4 | 05-Apr-2017 |
- | baju anak laki-laki | 2 | 4 | 02-Apr-2017 |
- +---------------------+----------+------+-------------+
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement