sql查询语句按条件统计字段值并在一个表中多列显示

2024-12-24 05:07:06
推荐回答(4个)
回答1:

select sum(case

             when con1 = 1 and con2 = 1 then

              count

             else

              0

           end) 三星笔记本,

       sum(case

             when con1 = 1 and con2 = 2 then

              count

             else

              0

           end) 三星台式机,

       sum(case

             when con1 = 2 and con2 = 1 then

              count

             else

              0

           end) 苹果笔记本,

       sum(case

             when con1 = 2 and con2 = 2 then

              count

             else

              0

           end) 苹果台式机

  from table_name;

回答2:

select sum(case when con1||con2='11' then count else 0 end) 三星笔记本,
sum(case when con1||con2='12' then count else 0 end) 三星台式机,
sum(case when con1||con2='22' then count else 0 end) 苹果笔记本,
sum(case when con1||con2='22' then count else 0 end) 苹果台式机
from table_name

另外用decode一样可以替代case when,效率一样

回答3:

select case when t.con1=1 and t.con2=1 then t.count else 0 end as '三星笔记本',
case when then else end from 表名字 t
就照这样写

回答4:

group by 按 con1 con2 分组 然后sum