sql - 如何为 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 中完成此任务?抱歉标题不清楚,我在翻译中迷路了。
解决方案
您想要的查询应该如下所示:
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;
如果这不起作用,那么问题就更微妙了——一些其他类型的隐藏字符。
推荐阅读
- c - 为什么 YACC 不产生 shift-reduce 冲突?
- java - 如何将坐标数组写入 Cloud Firestore
- java - 在 Java 11 桌面应用程序中使用 maven proguard
- javascript - 如何理解 javascript react 中的这段代码
- android-studio - 缺少类:com.fasterxml.jackson.core.type.TypeReference。R8:警告
- html - 过渡影响背景图像
- cron - 当我在 RedHat 中使用本地时间时,为什么我的 crontab 不工作?
- jmeter - jmeter中的403禁止错误,但api在邮递员中工作正常
- typescript - dtslint 失败,因为 DefinitiveTyped 中的依赖
- reactjs - 从 react-navigation v1 迁移到 v3.11 时遇到问题