Sql 查询具有多个条件的表
我有一张这样的桌子:Sql 查询具有多个条件的表,sql,sql-server,Sql,Sql Server,我有一张这样的桌子: Date | Product | purchases | sales | -----------+---------+-----------+--------+ 2019-01-01 | P1 | 2 | 1 | 2019-02-01 | P2 | 2 | 1 | 2019-01-02 | P1 | 2 | 2 | 2019-08-01 | P2
Date | Product | purchases | sales |
-----------+---------+-----------+--------+
2019-01-01 | P1 | 2 | 1 |
2019-02-01 | P2 | 2 | 1 |
2019-01-02 | P1 | 2 | 2 |
2019-08-01 | P2 | 8 | 8 |
2019-08-02 | P1 | 2 | 1 |
2019-08-03 | P2 | 8 | 8 |
Date | Product | purchases | sales | Stock
-----------+---------+------------+--------+-------
2019-08-31 | P1 | 2 | 1 | 2
2019-08-31 | P2 | 16 | 16 | 1
我想要一个查询,可以得到每个产品上个月的采购总额,在采购中,上个月每个产品的销售总额,在销售中,在我想要上个月最后一天的日期的日期,还有一个名为Stock的新专栏,计算每种产品的购买总额——从开始到本月第一天的销售总额,这不仅意味着最后一个月,而且意味着2019-09-01年之前的所有时间
此查询的结果应如下所示:
Date | Product | purchases | sales |
-----------+---------+-----------+--------+
2019-01-01 | P1 | 2 | 1 |
2019-02-01 | P2 | 2 | 1 |
2019-01-02 | P1 | 2 | 2 |
2019-08-01 | P2 | 8 | 8 |
2019-08-02 | P1 | 2 | 1 |
2019-08-03 | P2 | 8 | 8 |
Date | Product | purchases | sales | Stock
-----------+---------+------------+--------+-------
2019-08-31 | P1 | 2 | 1 | 2
2019-08-31 | P2 | 16 | 16 | 1
我尝试过此查询,但结果不好:
将SumZ作为库存,从t中选择SumZ购买sumsales作为库存
其中t.date和DATEADDDAY,-DAYGETDATE,GETDATE您似乎想要一个带有筛选的聚合查询:
select eomonth(date), product, sum(purchases), sum(sales),
sum(purchases) - sum(sales)
from t
where eomonth(date) = eomonth(dateadd(month, -1, getdate()))
group by eomonth(date), product;
编辑:
对于股票的累计金额,您可以执行以下操作:
select dp.*
from (select eomonth(date) as date, product,
sum(purchases) as purchases, sum(sales) as sales,
sum(sum(purchases) - sum(sales)) over (partition by product order by eomonth(date) as stock
from t
group by eomonth(date), product
) dp
where eomonth(date) = eomonth(dateadd(month, -1, getdate()));
是一个数字小提琴。你如何定义上个月?这个月是2019-09,上个月是2019-08,就像在示例中一样,你到目前为止尝试了什么???我应该把我尝试过的放在问题中,我再次编辑它以显示我想要的tried@Eric对这个问题有什么想法吗?我有个错误:文本,ntext,和图像数据类型不能进行比较或排序,除非使用IS NULL或LIKE运算符。@chawky。您不应该对这些列中的任何列使用这些类型。事实上,您不应该将它们用于任何列。修正你的数据!我修正了我的数据,但它给了我错误的结果:对于P1,当它应该是2时,库存是1;对于P2,当它应该是1时,库存是0;对于购买和销售以及日期,结果是好的@Gordon Linoff在您的查询中,库存只计算上一个月,当它应该计算到最后一个月之前的所有月份时末日month@chawky . . . 这澄清了你想做什么。你需要一个窗口函数。我更新了答案。