Sql 如何为第1列中的每个相同值以及第2列中的数据和创建新列?
我有这样一个数据库:Sql 如何为第1列中的每个相同值以及第2列中的数据和创建新列?,sql,plsql,Sql,Plsql,我有这样一个数据库: |productno | type | quantity | |180001 | hms1 | 15000 | |180001 | hms1 | 12400 | |180001 | hms1 | 13600 | |180001 | hms2 | 24599 | |180002 | pik | 88888 | |180002 | hms1 |
|productno | type | quantity |
|180001 | hms1 | 15000 |
|180001 | hms1 | 12400 |
|180001 | hms1 | 13600 |
|180001 | hms2 | 24599 |
|180002 | pik | 88888 |
|180002 | hms1 | 55000 |
|180002 | hms1 | 22500 |
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;
和列表继续。。。
我想要完成的是为每个产品编号选择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
但hms1返回null,如果我将else 0添加到sum函数,则返回零
如何在PL/SQL中实现这一点?对不起,标题不清楚,我在翻译中弄丢了 对所需内容的查询应如下所示:
|productno | type | quantity |
|180001 | hms1 | 15000 |
|180001 | hms1 | 12400 |
|180001 | hms1 | 13600 |
|180001 | hms2 | 24599 |
|180002 | pik | 88888 |
|180002 | hms1 | 55000 |
|180002 | hms1 | 22500 |
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;
如果这不起作用,那么问题就更微妙了——一些其他类型的隐藏字符。请先从数据库中按原样选择*,键入='hms1'。它应该在任何类型为hms1的列旁边放置一个TRUE。如果不是,您的类型列可能有前导空格。@OwlsSleeping。我不认为pivot语法有用。我可以使用条件聚合完成它所做的一切,甚至更多。我发现结果查询也更容易理解。