0

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

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来计算百分比——只是为了得到所有产品销售额的总和)

谢谢

4

2 回答 2

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; 
于 2013-04-04T11:31:05.560 回答
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; 

或者,如果您想要给定产品 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;
于 2013-04-04T11:23:38.217 回答