繁体   English   中英

SQL-如何获取每行的总和并在条件存在时将其放入,如果不存在则将其放入最后一行

[英]SQL- How to get the sum of each row and put it if condition exists, if does not exists put it in the last line

我有一张这样的桌子(还有很多名字)

name    Class Amount
Alex    C1     100
Brenda  AB     50        
Brenda  C1     100         
Alex    AB     200

我想遵循 output,对每个名称求和,但仅在 Class 列等于 C1 或没有 C1 时将其放在名称的最后一条记录中。

例如。 Alex 的总和是 300(100+200),而 Brenda 的总和是 150(100+50),Alex 在第一行有 C1,所以总和放在那一行而不是最后一行,brenda 没有Class C1,所以总和在 Brenda 的最后一行。

像这样:

name    Class Amount   Sum
Alex    C1     100     300
Brenda  AB     50       0
Brenda  AB     100     150    
Alex    AB     200      0

知道如何在 SQL 中做到这一点吗? (访问或 MySQL)

谢谢并恭祝安康

您可以在 MySQL 中使用 window 函数:

select t.*,
       (case when row_number() over (partition by name order by (class = 'C1') desc, amount desc) = 1
             then sum(amount) over (partition by name)
             else 0
        end) as sum_amount
from t;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM