获取每种类型的总uid

时间:2013-05-07 12:34:27

标签: mysql sql

我需要找到有多少用户带来了产品(注意:我不需要用户总数,只需要有多少用户)。

表名:买家

+-----+----------+---------+
| id  | products |    uid  |
|-----|----------|---------|
| 1   |  soap    |    2    |
| 2   |  h_oil   |    1    |
| 3   |  soap    |    3    |
| 4   |  tea     |    1    |
| 5   |  soap    |    2    |
| 6   |  h_oil   |    1    |
| 7   |  soap    |    3    |
| 8   |  tea     |    1    |
+-----+----------+---------+

我需要如下表所示的结果:

|-----|---------------|--------------|
| id  | product_name  |  total_user  |
|-----|---------------|--------------|
| 1   |  soap         |      2       |
| 2   |  h_oil        |      1       |
| 3   |  tea          |      1       |
|------------------------------------|

如何在MySQL查询中执行此操作?

5 个答案:

答案 0 :(得分:1)

您可以使用:

SELECT product_name, COUNT(*) AS total_user FROM buyer GROUP BY product_name;

答案 1 :(得分:1)

 SELECT products product_name, COUNT(DISTINCT uid) total_user FROM purchases GROUP BY products;

答案 2 :(得分:0)

像这样:

SELECT 
    COUNT(*) 
FROM
    buyer
GROUP BY
    products 

答案 3 :(得分:0)

简而言之,您正在寻找group by声明

SELECT uid, product_name, count(id) as total_user FROM buyer GROUP BY uid

在这里阅读更多内容:

答案 4 :(得分:0)

SELECT 
    COUNT(id) 
FROM
    buyer
GROUP BY
    products