Skip to content
Advertisement

How to get the sum of values in a table interval?

The question is very simple :-). I’m a beginner.

tables

Declare @startDate date,
Declare @endDate date

Select
d.ID,
d.Date as DateDocumet,
dt.id As TypeDocument,
p.Name as ProductName,
p.Price as Price,
d.qty

from Documents d
LEFT  join product p on d.ProductId = p.id  
LEFT  join DocumentType dt on d.DocumentTypeId = dt.id 

Result: enter image description here

A taskā€¦.. There are two date variables.

How to get the sum of values(qty) between dates(@startDate – @endDate).

How to get the sum of values(qty) up to @startDate.

How get the sum of values(qty) down to @endDate.

If DocumentType is 1. Then the value(qty) minus.

Advertisement

Answer

Looks like you need conditional aggregation SUM(CASE WHEN....

CROSS APPLY also makes it easier to pre-calculate the negative qty

Declare @startDate date;
Declare @endDate date;

Select
   SUM(CASE WHEN d.Date < @startDate THEN QtyToSum END),
   SUM(CASE WHEN d.Date >= @startDate AND d.Date < @endDate THEN QtyToSum END),
   SUM(CASE WHEN d.Date >= @endDate THEN QtyToSum END),
from Documents d
CROSS APPLY (VALUES (CASE WHEN d.DocumentTypeId = 1 THEN -d.qty ELSE d.qty END) ) AS v(QtyToSum)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement