使用不同的日期SQL Server求和

时间:2016-03-07 16:43:28

标签: sql

我有两张桌子,

表1是交易表

+----------+-----------+---------+------------+-----+
| IDOutlet | IDProduct | TrxType |  TrxDate   | Qty |
+----------+-----------+---------+------------+-----+
|      101 | ASD11     |       2 | 11/11/2015 |  15 |
|      101 | ASD11     |       3 | 11/14/2015 |  -3 |
|      101 | ASD11     |       3 | 11/17/2015 |  -6 |
|      101 | ASD11     |       2 | 11/22/2015 |   7 |
|      101 | ASD11     |       3 | 11/26/2015 |  -2 |
|      101 | ASD11     |       2 | 12/3/2015  |   1 |
|      101 | ASD11     |       3 | 12/9/2015  |  -3 |
|      101 | ASD11     |       3 | 12/11/2015 |  -2 |
|      101 | ASD11     |       2 | 12/12/2015 |   5 |
|      101 | FFD34     |       2 | 11/11/2015 |   9 |
|      101 | FFD34     |       3 | 11/14/2015 |  -3 |
|      101 | FFD34     |       2 | 11/16/2015 |   3 |
|      101 | FFD34     |       3 | 11/19/2015 |  -4 |
|      101 | FFD34     |       3 | 11/23/2015 |  -3 |
|      102 | FFD34     |       2 | 11/26/2015 |   2 |
|      102 | FFD34     |       2 | 11/28/2015 |   4 |
|      102 | FFD34     |       3 | 11/29/2015 |  -5 |
|      102 | FFD34     |       3 | 12/1/2015  |  -1 |
+----------+-----------+---------+------------+-----+

表2是opnametable

+----------+-----------+------------+-----------+
| IDOutlet | IDProduct | OpnameDate | QtyOpname |
+----------+-----------+------------+-----------+
|      101 | ASD11     | 11/20/2015 |         5 |
|      101 | FFD34     | 11/30/2015 |         5 |
|      102 | FFD34     | 11/30/2015 |         1 |
+----------+-----------+------------+-----------+

我想要这样的结果

+----------+-----------+------------+---------+
| IDOutlet | IDProduct | OpnameDate | Sum Qty |
+----------+-----------+------------+---------+
|      101 | ASD11     | 11/20/2015 |       6 |
|      101 | FFD34     | 11/20/2015 |       5 |
|      102 | FFD34     | 11/30/2015 |       1 |
+----------+-----------+------------+---------+

2 个答案:

答案 0 :(得分:2)

您可以在JOIN条件中使用日期比较:

SELECT  T2.IDOutlet,T2.IDProduct,T2.OpnameDate,SUM(T1.Qty) AS Sum_Qty
FROM opnametable T2
LEFT JOIN transaction T1
  ON T2.IDOUtlet = T1.IDOutlet
 AND T2.IDProduct = T1.IDProduct
 AND T1.TrxDate  <= T2.OpnameDate 
GROUP BY T2.IDOutlet,T2.IDProduct,T2.OpnameDate

我假设日期存储在适当的日期数据类型中,并且您希望包含OpnameDate

答案 1 :(得分:0)

试试这个

select o.IDOutlet,o.IDProduct,sum(t.Qty) as [Sum Qty]
from opnametable o left outer join transaction1 t on  o.IDOutlet=t.IDOutlet
and o.IDProduct=t.IDProduct and t.trxdate<o.OpnameDate
group by o.IDOutlet,o.IDProduct