SQL SUM of values between two dates calculated fields

旧巷老猫 提交于 2019-12-11 04:14:49

问题


I have this query, which returns null:

SELECT 
   SUM(sales) as [MAT]  
from 
   TABLE2 
where 
   Date1 between CONVERT(VARCHAR(23), DATEADD(MONTH, -11, Date1), 111) and 
                 CONVERT(VARCHAR(23), DATEADD(MONTH, 0, Date1), 111);

In the columns, date1 is in the format YYYY-DD-MM, which is why I convert it.

I want the sum of the amounts from each date by product (another field) between those two dates.

--UPDATE--

Hi, i already changed the format to DATETIME . Now the query looks like this:

SELECT 
   SUM(sales)as [MAT] 
from 
   TABLE2 
where 
   Date1 between DATEADD(MONTH,-11,Date1) and DATEADD(MONTH,0,Date1);

It shows me the total amount of all the products, and i want the total for each...any ideas? @DanBracuk


回答1:


assuming you've got a column in the table called 'partid', it would be something like this:

select partid,sum(sales)
from 
 TABLE2 
where 
 Date1 between DATEADD(MONTH,-11,Date1) and DATEADD(MONTH,0,Date1);
group by partid



回答2:


In Table2 what are the other columns? Specifically is the name of the product identified in the table?

I am pretty sure all you need is a Group By statement at the end. Something like

SELECT productName,sum(sales) 
FROM table 2 
WHERE date 1 between DATEADD(MONTH,-11,Date1) and DATEADD(MONTH,0,Date1) 
GROUP BY productName



回答3:


SQL SUM of values between two dates calculated fields

$sql =  "SELECT  `product_field_name`,
         SUM(CASE WHEN `DATE1_field_name` BETWEEN  '".$MINdate."' and '".$MAXdate."' THEN sales ELSE 0 END) AS 'MAT'
         FROM TABLE_name 
         GROUP BY `product_field_name`";



回答4:


If you need sum of the values for each date by product between those two dates, you shoul add date and product fields as a group by;

SELECT 
   Date1, product, SUM(sales)as [MAT] 
from 
   TABLE2 
where 
   Date1 between DATEADD(MONTH,-11,Date1) and DATEADD(MONTH,0,Date1)
group by Date1, product;


来源:https://stackoverflow.com/questions/17618748/sql-sum-of-values-between-two-dates-calculated-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!