SQL Server - 将结果从一行获取到另一行

问题描述 投票:-1回答:2

在我们的销售系统中,最后添加了折扣,但是当将这些数据移动到另一个系统时,我需要在每一行中都有折扣。

在这种情况下,有三组,它们与LineType 2和64分开。在第一组中,我需要将Forumula_discount = 15 line ID 972922的结果变为上面的四行,然后是其他组。

你能指导我如何在SQL服务器上的Select语句中解决这个问题。

此致,BG

sql sql-server select
2个回答
1
投票

您需要定义组,我认为您可以使用累积总和来定义组。然后使用窗口函数“传播”值:

select t.*,
       sum(formula_discount) over (partition by docno, grp) as imputed_formula_discount
from (select t.*,
             sum(case when linetype in (2, 64) then 1 else 0 end) over (partition by docno order by id) as grp
      from t
     ) t;

0
投票

你真正需要的是在同一张表中的2个视图。一种观点代表产品和其他折扣。这是典型的旧学校系统。然后,您可以根据线型将表的两个不同视图相互连接。我只是使用自联接而不是创建实际的数据库视图。我会将表格别名两次... p代表产品,d代表折扣。

基本上,“产品”的线型为1,折扣为64.您从未提及表的名称,但我将其称为“dbtable”。试试这个。

select p.docno, p.id, p.linetype, p.type, p.item_NO, d.formula_discount
from dbtable p inner join dbtable d
  on p.linetype = d.linetype
  and d.linetype = 64 -- This limits 'd' rows to just discounts
where p.linetype = 1;

请注意,您实际上可以为每个数据库视图定义数据库视图,以使其更具体。

© www.soinside.com 2019 - 2024. All rights reserved.