【问题标题】:I want you to help me prepare a detailed customer statement report我希望你帮我准备一份详细的客户报表报告
【发布时间】:2017-12-04 07:49:47
【问题描述】:

报告的目的是提供客户的详细帐户,显示两个日期之间每次交易后的余额以及开始日期之前的余额

我有一个来自 SQL Server 中三个表的视图。我想在开始和结束日期的三个基础日期从中提取证据。但是,以前的余额会在报告开头显示在客户端上。知道视图中没有余额列怎么能做到这一点。 我使用存储过程

我希望报告输出是这样的

我使用这个代码,但我有问题

declare @id_customer int 
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]

一些记录来了

picture

【问题讨论】:

  • 目前你做了什么?您遇到了哪些错误?
  • 请注意,视图中不存在 Balance 列
  • 虽然任何人都可以为您编码,并且可能有人这样做要求“为我做我的工作”是 off-topic 注意非视距问题会吸引投票
  • 我更新了我的问题,希望对你有用

标签: sql sql-server tsql stored-procedures


【解决方案1】:

试试这个,没有示例数据很难猜测,但应该可以。 我假设事务 ID 是增量的,如果我错了,请纠正我:

declare @id_customer int = 2
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)   
   from initial b   
   where b.[date]<=r.[date] and b.[id]<r.[id] ) +
   r.debit - r.credit ,r.debit-r.credit),r.date

  from initial r

)

 select [Operation type] = r.type,
        reference_no = r.id,
        [description] = r.description,
        [Debit] = r.debit,
        [Credit] = r.credit,
        [Balance] = b.balance,
        [Date] = r.date
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 group by r.id, r.type,r.debit,r.credit,r.date,r.description,b.balance
 order by r.[date]

【讨论】:

  • 运行此查询并发布结果:“Select * FROM result where ID=3”
  • 当有发票和收据类似的 id 号重复时会发生重复,因此我需要一个唯一的密钥来执行以下代码中的比较过程
猜你喜欢
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多