在MySQL中,您可以使用COUNT()
函數(shù)結(jié)合GROUP BY
子句來(lái)進(jìn)行分組統(tǒng)計(jì)。以下是一個(gè)簡(jiǎn)單的示例:
假設(shè)您有一個(gè)名為orders
的表,其中包含以下數(shù)據(jù):
order_id | customer_id | product_id | order_date |
---|---|---|---|
1 | 1 | 101 | 2021-06-01 |
2 | 1 | 102 | 2021-06-01 |
3 | 2 | 101 | 2021-06-02 |
4 | 2 | 102 | 2021-06-02 |
5 | 3 | 101 | 2021-06-03 |
現(xiàn)在,假設(shè)您想要統(tǒng)計(jì)每個(gè)客戶購(gòu)買的不同產(chǎn)品的數(shù)量。您可以使用以下查詢:
SELECT customer_id, COUNT(DISTINCT product_id) as product_count
FROM orders
GROUP BY customer_id;
這將返回以下結(jié)果:
customer_id | product_count |
---|---|
1 | 2 |
2 | 2 |
3 | 1 |
在這個(gè)例子中,我們使用COUNT(DISTINCT column_name)
來(lái)計(jì)算每個(gè)分組中不同值的數(shù)量。GROUP BY
子句根據(jù)customer_id
對(duì)結(jié)果進(jìn)行分組,然后我們計(jì)算每個(gè)分組中不同product_id
的數(shù)量。