Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Getting the sum of a value for two seperate date ranges in same column and in a single MySQL query

I have table like below and i'm trying to write single query for fetch the date range data as well as sum of price. My table definitions are as below

Sale table

id_sale date       time
  1     2014-05-05 12.30 am  
  2     2014-05-06 10.30 am 
  3     2014-05-25 12.30 am   

Sale Product table

   id_sale_product id_sale price  quantity  id_product
      1              1     10.00   1           1
      2              1     20.00   1           2
      3              2     20.00   3           5
      4              3     20.00   4           6

I want to filter by date in sale table and get the sum of the price * quantity = total for every date ie,2014-05-05,2014-05-06..etc

I have tried below query

$query = 'SELECT sp.`id_product_type`,sp.`id_product`,sp.`quantity`,sp.`price`,s.`date`
              , SUM(IF(s.`date` BETWEEN "'.$datepickerFrom.'" AND "'.$datepickerTo.'",sp.`price` * sp.`quantity`,0)) AS A
              FROM `'._DB_PREFIX_.'sale_product` sp
              LEFT JOIN '._DB_PREFIX_.'sales s ON (sp.id_sale = s.id_sale) 
              WHERE (s.`date` BETWEEN "'.$datepickerFrom.'" AND "'.$datepickerTo.'")';

The output should be :

Example: Date
01/01/2013    Rs.10000
02/01/2013    Rs.140000
03/01/2013    Rs.8000

Example: Month
January     Rs. 2,00,000
Feburary    Rs. 2,20,000
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try This ....

select a.date,sum(b.qty * b.price) As sum from sales As a, product As b where DATE_FORMAT(a.date,'%d-%m-%Y') between '27-05-2014' AND '28-05-2014' and a.id_sale=b.id_sale group by a.date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...