1

我的数据库中有两个视图,这是它们的结构:

表 1(库存产品条目):

---------------------------------------
| Date     | Product     | Quantity   |
---------------------------------------
|2013-06-06| Procuct001  | 40         |
---------------------------------------

表 2(库存产品输出):

---------------------------------------
| Date     | Product     | Quantity   |
---------------------------------------
|2013-06-07| Procuct001  | 15         |
---------------------------------------
|2013-06-08| Procuct001  | 5          |
---------------------------------------

我想要第三个视图(或表格),我将在其中存储所有库存的变动(条目或输出),但我不想存储输入或检索的数量,而是存储差异(这意味着库存的余额)。在我们的例子中,新表应该包含:

表 3(库存余额):

---------------------------------------
| Date     | Product     | Quantity   |
---------------------------------------
|2013-06-06| Procuct001  | 40         |
---------------------------------------
|2013-06-07| Procuct001  | 25         |
---------------------------------------
|2013-06-07| Procuct001  | 20         |
---------------------------------------

我正在使用带有 SP1 的 SQL Server 2012。

4

1 回答 1

0

这是使用公用表表达式的一个选项,ROW_NUMBER用于播种您的列表(按产品分组):

with cte as (
  select dt, product, quantity, row_number() over (partition by product order by dt) rn
  from (
    select * from t1
    union
    select * from t2
    ) t
  ) 
select c.dt, c.product,
  c2.quantity - coalesce(sum(c3.quantity),0) runningty 
from cte c
  inner join (
    select product, quantity
    from cte
    where rn = 1) c2 on c.product = c2.product
  left join cte c3 on c.product = c3.product and c3.rn <= c.rn and c3.rn <> 1
group by c.dt, c.product, c2.quantity

根据您的数据,您可能不需要额外的内部连接来获得您的“第一条”记录——您也许可以使用类似这样的东西:

with cte as (
  select dt, product, quantity, row_number() over (partition by product order by dt) rn
  from (
    select * from t1
    union
    select * from t2
    ) t
  ) 
select c.dt, c.product,
  max(c.quantity) over (partition by c.product) - coalesce(sum(c3.quantity),0) runningty 
from cte c
  left join cte c3 on c.product = c3.product and c3.rn <= c.rn and c3.rn <> 1
group by c.dt, c.product, c.quantity
于 2013-06-17T03:24:46.050 回答