查询具有多个条件的表

时间:2019-09-18 14:29:32

标签: 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      | 8         | 8      |
2019-08-02 | P1      | 2         | 1      |
2019-08-03 | P2      | 8         | 8      |

我想要一个查询,该查询将为我提供每个产品的上个月的购买总和(以购买为单位),上个月内每个产品的销售总和(以销售为单位),我想要上次日期的日期上个月的一天,还有一个名为Stock的新列,该列为每种产品计算购买总和-从开始到当月第一天的销售总和(不仅仅代表最后的飞蛾,还包括一直到2019-09-01)。

此查询的结果应如下所示:

Date       | Product | purchases  | sales  | Stock
-----------+---------+------------+--------+-------
2019-08-31 | P1      |     2      |    1   |   2
2019-08-31 | P2      |    16      |   16   |   1

我尝试了此查询,但结果不理想: 以SumZ作为(从t中选择总和(购买)-总和(销售)作为库存     t.date

选择日期,产品,购买,销售,SumZ.stock 从t到SumZ DATEADD(mm,DATEDIFF(mm,0,GETDATE())-1,0)之间的日期        AND DATEADD(DAY,-(DAY(GETDATE())),GETDATE())

1 个答案:

答案 0 :(得分:2)

您似乎想要带过滤的聚合查询:

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;

编辑:

对于stock的累计金额,您可以执行以下操作:

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()));

Here是db <>小提琴。