问题
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