在MySQL中,分组排序可以通过GROUP BY
和ORDER BY
子句来实现。以下是一些常见的分组排序方法:
- 基本分组排序 :
SELECT column1, column2, COUNT(*)
FROM table
GROUP BY column1
ORDER BY column2 DESC;
- 使用聚合函数排序 :
SELECT column1, column2, COUNT(*)
FROM table
GROUP BY column1
ORDER BY COUNT(*) DESC;
-
使用
CASE
语句排序 :
SELECT column1, column2
FROM table
ORDER BY CASE
WHEN column1 = 'value1' THEN 1
WHEN column1 = 'value2' THEN 2
ELSE 3
END;
- 使用窗口函数(MySQL 8.0及以上版本) :
SELECT PurchaseOrderID, ProductID, Quantity, UnitPrice,
RANK() OVER(PARTITION BY PurchaseOrderID ORDER BY Quantity DESC) as ranking
FROM purchase_order_details;
- 使用子查询和变量 :
SELECT @r:= CASE WHEN @rank=te.package_item_id THEN @r+1 ELSE 1 END AS quoteRanking,
@rank:=te.package_item_id AS TYPE,
te.*
FROM (
SELECT pqi.item_Name itemName, pqi.`package_item_id`, pt.bidder_Name_Cn bidderName, pt.`bidder_id`,
ROUND(MAX(pqi.unit_Price_Taxed), 2) quotePrice,
DATE_FORMAT(pqi.create_Time, '%Y-%m-%d %H:%i:%s') quoteTime,
pqi.price_Unit priceUnit,
pqi.price_Currency priceCurrency
FROM ptb_quote pt, ptb_quote_item pqi
WHERE pt.id = pqi.quote_id AND pt.package_id = '10937' AND pqi.unit_Price_Taxed > 0
) as te, (SELECT @rank:=0) as init
ORDER BY te.package_item_id;
-
使用
LIMIT
和HAVING
获取每个分组的特定数据 :
SELECT t.*
FROM (
SELECT e.*
FROM error_record e
WHERE e.status > 0 AND e.error_type > 0
ORDER BY e.status
LIMIT 1000
) as t
GROUP BY t.error_type;
以上示例展示了如何在MySQL中执行分组排序的不同方法。请根据您的具体需求选择合适的方法