【问题标题】:Write a SQL query to calculate the balance in a card [closed]编写一个 SQL 查询来计算卡中的余额 [关闭]
【发布时间】:2021-02-08 14:07:40
【问题描述】:

你能帮我计算每个季度的余额吗

数据表

创建表格的脚本:

创建表 CardTransactions ( CardId varchar(10), Trans_num int, 四分之一 varchar(25), 交易金额浮动, Balance_Trans 浮动 )

插入 CardTransactions 值

('Card1', 1, 'FQ-2013-4', 10 , 5 ),
('Card1', 2, 'FQ-2013-4', 3.65, 1.35 ),
('Card1', 3, 'FQ-2014-1', -10 , 11.35 ),
('Card1', 4, 'FQ-2014-1', -10 , 21.35 ), ('Card1', 5, 'FQ-2014-1', 4.2 , 17.15 ), ('Card1', 6, 'FQ-2014-3', 2, 15.15), ('Card1', 7, 'FQ-2014-3', 1.15, 14),
('Card1', 8, 'FQ-2014-4', -20 , 34 ),
('Card1', 9, 'FQ-2014-4', 5.15, 28.85), ('Card1', 10, 'FQ-2015-3', 4 , 24.85), ('Card1', 11, 'FQ-2015-3', 2.5 , 22.35 ), ('Card1', 12, 'FQ-2015-3', 2.35, 20)

从 CardTransactions 中选择 *;

预期结果:需要这样的结果

我试过像这样运行这个查询,但没有用

select 
   distinct ct1.CardId, 
   ct1.Quarter,
   ct2.Balance_Trans-ct1.TransactionAmount balance, 
   ROW_NUMBER() over(partition by ct1.Quarter order by ct1.Quarter) rn
from CardTransactions ct1
join  CardTransactions ct2
   on ct1.Trans_num >= ct2.Trans_num;

【问题讨论】:

  • 如果您使用受支持的 SQL Server 版本,这将容易。 2008 不支持不使用“古怪”功能或三角连接的累积和。考虑到 SQL Server 2008 已经停止支持一年多了,我建议已经过了更新时间。
  • “不工作”不是问题描述。应该发生什么?会发生什么?
  • 我在 SQL Server 2016 中运行它。你能帮忙分享这个 SQL 查询吗?
  • "我在 SQL Server 2016 中运行这个" 那你为什么要标记sql-server-2008
  • @underscore_d 我也试过这样 select distinct ct1.CardId, ct1.Quarter, null from CardTransactions ct1 UNION ALL Select null, null,cast(ct1.Balance_Trans as varchar(50)) - -ct1.TransactionAmount,ct1.Balance_Trans-ct1.TransactionAmount balance from CardTransactions ct1 但是,预期的结果是余额计算没有到来。

标签: sql sql-server tsql sql-server-2012 sql-server-2016


【解决方案1】:

您似乎想要每张卡片和每季度的最后一个 balance_trans

一种方法是:

select ct.*
from (select ct.*,
             row_number() over (partition by cardid, quarter order by trans_num desc) as seqnum
      from CardTransactions ct
     ) ct
where seqnum = 1;

你也可以这样表达:

select ct.*
from CardTransactions ct
where ct.trans_num = (select max(ct2.trans_num)
                      from CardTransactions ct2
                      where ct2.cardid = ct.cardid and 
                            ct2.quarter = ct.quarter
                     );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2020-03-25
    • 2017-06-11
    • 1970-01-01
    • 2022-10-17
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多