【问题标题】:SQL operations in same table同一张表中的 SQL 操作
【发布时间】:2016-11-24 12:27:43
【问题描述】:

我有一个列名为:

  1. ID (int)(非唯一)
  2. 类型(varchar)
  3. 金额(十进制)

对于每个 id,都有两个“类型”的记录。称为费用和折扣,有两种不同的金额。 我想从费用金额中扣除折扣金额并获得每个 ID 的最终金额。 作为 Id '2' 的示例,我的收费金额可能为 200,折扣金额为 30,因此我希望 Id '2' 的结果为 170

我想不出一个干净的方法来做到这一点。

【问题讨论】:

  • 当您制作此表时,您应该将折扣设为负数。

标签: mysql sql datatable


【解决方案1】:

我有一些假设,这将帮助你。

Create Table Transactions(ID Int,Type varchar(255),
                    Amount int)

 Insert Into Transactions Values(1,'Charge',10)
 Insert Into Transactions Values(1,'Discount',2)
 Insert Into Transactions Values(2,'Charge',15)
   Insert Into Transactions Values(2,'Discount',3)
  Insert Into Transactions Values(3,'Charge',20)
  Insert Into Transactions Values(3,'Discount',3)

现在我为您创建了我的查询解决方案。

Select  T1.ID,T1.Type,T1.Amount-T2.amount  from Transactions T1
 join Transactions T2
 on T1.ID=T2.ID
 and T1.Type<>T2.Type

您可以使用 where 子句过滤您的答案

 Select  T1.ID,T1.Type,T1.Amount-T2.amount  from Transactions T1
 join Transactions T2
 on T1.ID=T2.ID
 and T1.Type<>T2.Type
 where T1.Type='Charge'

请回复。

【讨论】:

    【解决方案2】:

    如果您可以绝对确定除了 'charge' 和 'discount' 之外没有其他类型的变体,那么这个查询应该可以工作:

    select ID, 
    sum(case 
          when Type = 'charge' then Amount 
          when Type = 'discount' then Amount*-1
        end) as final_amount
    from my_table
    group by ID
    

    它的工作原理是先检查类型是什么,然后再决定对总和做出贡献。如果值为'charge',则使用金额,否则,如果值为'discount',则取反金额并从总和中扣除。

    假设:

    1. 'charge'discount 是 type 唯一可能的值
    2. 无论类型如何,金额始终为正数

    【讨论】:

    • 如果我想用 final_amount 替换费用行中的金额怎么办?
    猜你喜欢
    • 2018-12-24
    • 2021-10-19
    • 1970-01-01
    • 2021-09-17
    • 2016-03-12
    • 2013-03-15
    • 2017-07-17
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多