MySQLの各グループから上位N行を選択する必要がある場合があります。 MySQLでグループごとに上位N行を選択する方法は次のとおりです。これを使用して、グループごとに上位n件の結果を取得したり、カテゴリごとに上位10件のレコードを選択したり、各グループの最初のレコードを選択したりできます。
MySQLはグループごとに上位N行を選択します
グループごとに上位N行を選択する手順は次のとおりです。次のテーブルがあるとしますorders(id、product、amount)
mysql> create table product_orders(id int,product varchar(255),amount int);
mysql> insert into product_orders(id, product, amount)
values(1,'A',250),(2,'B',150),(3,'C',200),
(4,'A',250),(5,'B',210),(6,'C',125),
(7,'A',350),(8,'B',225),(9,'C',150);
mysql> select * from product_orders;
+------+---------+--------+
| id | product | amount |
+------+---------+--------+
| 1 | A | 250 |
| 2 | B | 150 |
| 3 | C | 200 |
| 4 | A | 250 |
| 5 | B | 210 |
| 6 | C | 125 |
| 7 | A | 350 |
| 8 | B | 225 |
| 9 | C | 150 |
+------+---------+--------+
ボーナスリード:MySQLで先週のデータを取得する方法
MySQLでグループごとに上位N行を選択する方法
まず、グループ内の各行をランク付けします( product 列)次のSQLクエリを使用します。
mysql> SELECT id, product, amount,
@product_rank := IF(@current_product = product, @product_rank + 1, 1)
AS product_rank,
@current_product := product
FROM product_orders
ORDER BY product, amount desc;
+------+---------+--------+--------------+-----------------------------+
| id | product | amount | product_rank | @current_product := product |
+------+---------+--------+--------------+-----------------------------+
| 7 | A | 350 | 1 | A |
| 1 | A | 250 | 2 | A |
| 4 | A | 250 | 3 | A |
| 8 | B | 225 | 1 | B |
| 5 | B | 210 | 2 | B |
| 2 | B | 150 | 3 | B |
| 3 | C | 200 | 1 | C |
| 9 | C | 150 | 2 | C |
| 6 | C | 125 | 3 | C |
+------+---------+--------+--------------+-----------------------------+
上記のクエリでは、最初にグループ内の各レコードを金額列で降順で並べ替えてから、ランク付けしました。金額の昇順で並べ替える場合は、ORDERby句を変更することで並べ替えることができます。
SELECT id, product, amount,
@product_rank := IF(@current_product = product, @product_rank + 1, 1)
AS product_rank,
@current_product := product
FROM product_orders
ORDER BY product, amount asc;
次に、上記のクエリをサブクエリとして使用して、グループごとに上位N行を選択します(たとえば、各カテゴリの上位2行)。
ボーナスリード:MySQLコピーデータベース
グループごとに上位2行を選択する方法
上記の方法を使用して各グループの上位2行を選択するSQLクエリは次のとおりです。上記のクエリをサブクエリとして使用し、ランクが2以下の行を選択します。
mysql> select id, product, amount from (
SELECT id, product, amount,
@product_rank := IF(@current_product = product, @product_rank + 1, 1)
AS product_rank,
@current_product := product
FROM product_orders
ORDER BY product, amount desc) ranked_rows
where product_rank<=2;
+------+---------+--------+
| id | product | amount |
+------+---------+--------+
| 7 | A | 350 |
| 1 | A | 250 |
| 8 | B | 225 |
| 5 | B | 210 |
| 3 | C | 200 |
| 9 | C | 150 |
+------+---------+--------+
ボーナス読み取り:MySQL Insert into Select
グループごとに上位10行を選択する方法
同様に、次のクエリを使用して、各グループから上位10行を選択できます。
mysql> select id, product, amount from (
SELECT id, product, amount,
@product_rank := IF(@current_product = product, @product_rank + 1, 1)
AS product_rank,
@current_product := product
FROM product_orders
ORDER BY product, amount desc) ranked_rows
where product_rank<=10;
うまくいけば、MySQLでグループごとに上位N行を簡単に選択できるようになりました。
Ubiqを使用すると、データを数分で簡単に視覚化し、リアルタイムのダッシュボードで監視できます。今日お試しください。