0

I have a table (sales) which has four columns;

id, user_id, product_id, and date_added.

I need to count the number of products with a certain id which have been sold by a user, and also get an overall count of products sold by that user in the current month.

I cant manage to sum the total products. I have;

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

how do I sum the total sales for a user, so I can get a percentage of total sales which are a specific product_id?

I expect my output to look something like this;

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

where total is the total number of sales made by the user.

(Is should mention that I don't need mysql to calculate the percentage - just to get the sum of all product sales)

thanks

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 に答える