MySQL经典练习题(三)

  • 查询出不一样的表结构

原表:

MySQL经典练习题(三)_第1张图片

查询出这样的表结构:

MySQL经典练习题(三)_第2张图片

代码:

用多表连接做

select t1.year, m1, m2, m3, m4 from 
(select year, amount as m1 from test1 where month = 1) as t1 
inner join 
(select year, amount as m2 from test1 where month = 2) as t2 
inner join 
(select year, amount as m3 from test1 where month = 3) as t3
inner join 
(select year, amount as m4 from test1 where month = 4) as t4
on t1.year=t2.year and t2.year=t3.year and t3.year=t4.year; 
  • 合并表中数据

原表

MySQL经典练习题(三)_第3张图片

其中:p_id为产品ID,p_num为产品库存量,s_id为仓库ID。

利用case when语句进行操作:

select p_id,
    sum(case when s_id=1 then p_num else 0 end) as s1_id,
    sum(case when s_id=2 then p_num else 0 end) as s2_id,
    sum(case when s_id=3 then p_num else 0 end) as s3_id
from test1 group by p_id;

结果:

MySQL经典练习题(三)_第4张图片

代码解释:

MySQL语句的书写顺序为:

select (输出)   from (获取数据)  where(过滤)  group by (分组) having(过滤) order by (排序)   limit(限定)

MySQL语句的执行顺序为: 

先from,在执行where,group by ,select, having,order by ,limit

1. 首先,我们选择出p_id对应的每个s_id的值,没有值的默认为0

select p_id,
    (case when s_id=1 then p_num else 0 end) as s1_id,
    (case when s_id=2 then p_num else 0 end) as s2_id,
    (case when s_id=3 then p_num else 0 end) as s3_id
from test1;

结果:

MySQL经典练习题(三)_第5张图片

2. 然后,为了得到1 2 3的形式,我们需要对p_id进行分组:

select p_id,
    (case when s_id=1 then p_num else 0 end) as s1_id,
    (case when s_id=2 then p_num else 0 end) as s2_id,
    (case when s_id=3 then p_num else 0 end) as s3_id
from test1 group by p_id;

结果:可以看出只有s1_id有值,其他为0。这是因为在分组的时候,默认只取了每个组的第一行。

MySQL经典练习题(三)_第6张图片

3. 因此,为了得到每个p_id 对应的 s_id中的全部值,需要进行sum每个s_id的p_um

select p_id,
    sum(case when s_id=1 then p_num else 0 end) as s1_id,
    sum(case when s_id=2 then p_num else 0 end) as s2_id,
    sum(case when s_id=3 then p_num else 0 end) as s3_id
from test1 group by p_id;

结果:

MySQL经典练习题(三)_第7张图片

你可能感兴趣的:(MySQL)