SQL查同一个字段输出两列?

如图,怎么从这个数据源中,写一个SQL语句查出code开头为1的quantity之和为一列,以及code开头为2的quantity之和为另一列

你好,按照你问题是需要按year分组,并且组内按照计算code开头为1的quantity之和以及code开头为2的quantity之和的数据。首先分析,既然需要按照year分组,那么就需要用到group by 那么 就可以写出如下:select year , xx, xx from 表名 group by year如何计算组内code开头为1的quantity之和以及code开头为2的quantity之和的数据,那么需要用到sum,并且分别刷选出code开头为1和code开头为2的数据即可。完整SQL如下:select year, sum (case when quantitiy like '%1' then quantitiy else 0 end as ) as 开头为1的quantity之和为一列, sum (case when quantitiy like '%2' then quantitiy else 0 end as ) as 开头为2的quantity之和为一列  from 表名  group by year
温馨提示:答案为网友推荐,仅供参考
第1个回答  2022-08-07
select sum(quantity)from table where code like “1%”
select sum(quantity)from table where code like “2%”
相似回答