MySQL COUNT where和COUNT all

时间:2013-04-04 11:06:08

标签: mysql

我有一个表(销售),有四列;

id, user_id, product_id, and date_added.

我需要计算用户已售出的具有特定ID的产品数量,并获得该用户在当月销售的产品的总数。

我无法总结产品总数。我有;

SELECT user_id, product_id, count(user_id) 
FROM sales 
WHERE MONTH(date_added) = MONTH(CURRENT_DATE) 
GROUP BY user_id, product_id; 

如何计算用户的总销售额,以便获得特定product_id的总销售额百分比?

我希望我的输出看起来像这样;

|----------|----------|----------|----------|
|user_id   |product_id|sales     |total     |
|----------|----------|----------|----------|
|1         |4         |6         |82        |
|2         |4         |3         |121       |
|3         |4         |8         |93        |      
|----------|----------|----------|----------|

其中total是用户的总销售数量。

(应该提一下,我不需要mysql来计算百分比 - 只是为了得到所有产品销售的总和)

谢谢

2 个答案:

答案 0 :(得分:1)

您必须使用子查询,因为您依靠聚合函数来进行计数

SELECT user_id, @pid:= product_id as product_id, count(user_id),
         (SELECT count(*)
          FROM sales
          WHERE MONTH(date_added) = MONTH( now() )
               AND product_id = @pid
          group by user_id
         ) as total_product_sales
FROM sales 
WHERE MONTH(date_added) = MONTH( now() ) 
GROUP BY user_id, product_id; 

答案 1 :(得分:0)

实际上我并不太了解你想要的......

此查询将为您提供给定用户的“小计”

 SELECT product_id, count(user_id) 
 FROM sales 
 WHERE MONTH(date_added) = MONTH(CURRENT_DATE) 
   AND user_id='YOUR_USER_ID'
 GROUP BY product_id with rollup; 

OR 如果您希望给出产品ID和当前月份的用户ID的总体百分比:

 SELECT 
        PARTIAL_SALES/TOTAL_SALES*100 
 FROM
      (SELECT USER_ID,
              count(user_id) AS PARTIAL_SALES
         FROM sales 
              WHERE MONTH(date_added) = MONTH(CURRENT_DATE) 
              AND user_id='YOUR_USER_ID'
              AND PRODUCT_ID='YOUR_PRODUCT_ID'
          GROUP BY USER_ID) AS PARTIAL,
      (SELECT USER_ID, 
              count(user_id) as TOTAL_SALES
         FROM sales 
              WHERE MONTH(date_added) = MONTH(CURRENT_DATE) 
          GROUP BY USER_id) AS TOTAL1
 WHERE PARTIAL.USER_ID=TOTAL.USER_ID;