mysql grouping如何實(shí)現(xiàn)多條件分組

小樊
111
2024-07-17 22:10:50
欄目: 云計(jì)算

要在MySQL中實(shí)現(xiàn)多條件分組,可以使用GROUP BY子句和HAVING子句來(lái)實(shí)現(xiàn)。下面是一個(gè)示例,演示如何根據(jù)多個(gè)條件對(duì)數(shù)據(jù)進(jìn)行分組:

假設(shè)我們有一個(gè)名為orders的表,包含以下字段:order_id, customer_id, product_idquantity。我們想要按照customer_idproduct_id對(duì)數(shù)據(jù)進(jìn)行分組,并且只選擇那些購(gòu)買(mǎi)數(shù)量大于10的訂單。

SELECT customer_id, product_id, SUM(quantity) AS total_quantity
FROM orders
GROUP BY customer_id, product_id
HAVING total_quantity > 10;

在上面的例子中,我們首先對(duì)orders表進(jìn)行分組,根據(jù)customer_idproduct_id進(jìn)行分組。然后使用HAVING子句來(lái)篩選出購(gòu)買(mǎi)數(shù)量大于10的訂單。最后,我們選擇customer_idproduct_id字段,并計(jì)算每個(gè)組的總購(gòu)買(mǎi)數(shù)量。

0