首页 > 解决方案 > 如何为 column1 中的每个相同值以及它们的数据以及它们在 column2 中的总和创建一个新列?

问题描述

我有一个这样的数据库:

    |productno | type | quantity |    
    |180001   | hms1 | 15000  |    
    |180001   | hms1 | 12400  |    
    |180001   | hms1 | 13600  |    
    |180001   | hms2 | 24599  | 
    |180002   | pik  | 88888  |    
    |180002   | hms1 | 55000  |    
    |180002   | hms1 | 22500  |    

并列出 contuniues... 我想要完成的是为每个产品号选择 hms1 的总和(或所有其他值),就像这样。

select productno, hms1, hms2, pik    
from database

结果应该是这样的

|productno| hms1| hms2| pik |    
|----------------------------     
|180001  | 41000 | 24599 |  0   |      
|180002  | 77500 |   0  | 88888 |

类型列中共有 5 种类型的值。所以不需要做一些自动化的事情。我尝试像这样使用 sum :

select productNo, sum (case when type='hms1' then quantity end) as hms1   
from database group by productNo

但是如果我将“else 0”添加到 sum 函数,hms1 返回 null 或零。

如何在 PL/SQL 中完成此任务?抱歉标题不清楚,我在翻译中迷路了。

标签: sqlplsql

解决方案


您想要的查询应该如下所示:

select productNo,
       sum(case when type = 'hms1' then quantity end) as hms1, 
       sum(case when type = 'hms2' then quantity end) as hms2, 
       sum(case when type = 'pik' then quantity end) as pik 
from database
group by productNo;

如果没有匹配项,则字符串常量不是您所期望的。一个常见的问题是开头或结尾的空格,因此您可以尝试:

select productNo,
       sum(case when trim(type) = 'hms1' then quantity end) as hms1, 
       sum(case when trim(type) = 'hms2' then quantity end) as hms2, 
       sum(case when trim(type) = 'pik' then quantity end) as pik 
from database
group by productNo;

如果这不起作用,那么问题就更微妙了——一些其他类型的隐藏字符。


推荐阅读