【问题标题】:how to include below subquery into store proc [closed]如何将以下子查询包含到存储过程中[关闭]
【发布时间】:2021-07-01 20:51:34
【问题描述】:
   with cte as
    (
    select trd_nbr,[date],sum(case when txn_typ='A' then abs(amount) else 0 end) 
     amountforA,
    sum(case when txn_typ='B' then abs(amount) else 0 end) amountforB, 
    sum(case when txn_typ='C' then abs(amount) else 0 end) amountforC
    from table1
    group by trd_nbr,[date]
     )
    select trd_nbr,[date], 
      (case when amountforA=amountforB and amountforB=amountforC then amountforC 
    else amountforA-amountforC end) Amount,
     (case when amountforA=amountforB and amountforB=amountforC then 'M' else 
      'NM' end) Matched
      from cte WHERE amountforA>0 and amountforB>0 and amountforC>0

如何将上述查询用于存储过程

 create proc proc name()
    begin 
    select amount, matched ,...from table1 
  where condition.. 
union all 
select column1, column2.... from table2
    where condition.. 
    end;

这里的数量和匹配列取自 with 子句。如何使用它..

【问题讨论】:

  • 对于这两种情况,您都提到了same logic for C and B。你能举一些C and B 的例子吗?也请展示你的尝试
  • 是的,如果 B 和 C 的记录公共列和总金额匹配,则单独显示 c。如果不匹配,则 B-C。
  • 你需要展示你的预期结果和你的尝试。
  • 场景 1 输出:C 金额 = 4000,单行显示交易编号 1 场景 2 输出:C 金额 = 10000-5000 = 5000,单行显示交易编号 2 C 金额 = 6000-2000 = 4000 单行交易号 3

标签: sql sql-server


【解决方案1】:

如果事务类型是固定的,那么可以使用pivot 轻松实现。请尝试以下方法:

drop table if exists #temp
select *
into #temp
from
(
    select trd_nbr, txn_typ, sum(abs(amount)) total
    from tab t
    group by trd_nbr, txn_typ
)t
pivot 
(
    sum(total) for txn_typ in ([A], [B], [C])
)pvt

select trd_nbr, case when C=A then C else A-C end as Final_C_amount
from #temp

您也可以检查 B 和 C。

请找到 dbfiddle here

【讨论】:

  • 当我在数据库中实现时。我得到了错误的记录。在这里,我们仅根据金额列的总和进行匹配和不匹配。我们需要将其他常见列(如 trade_nbr、日期与 A 的总和)与 C 的常见列(如 trade_nbr、日期与 C 的总和)进行匹配。我们可以根据这个条件过滤记录。对于匹配和不匹配的..我们需要在匹配和不匹配的条件下添加带有数量列总和的公共列..你能在同一个sql中实现这个逻辑吗
  • @RagavendraDevraj 抱歉延迟回复,您能否提供您需要的确切输出(dbfiddle 链接),因为我从您的笔记中不太清楚?您需要添加 Amount 和 Matched 列的基表的所有记录吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-12
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
  • 2016-09-10
  • 2011-07-02
  • 2017-01-09
  • 1970-01-01
相关资源
最近更新 更多