当前位置:   article > 正文

SQL进阶之路06:关联子查询

关联子查询

其实,在平日数据库使用中对同一行数据进列的比较很简单,只需要在WHERE添加条件即可!但是如果对于不同行数据的数据进行比较可能就没有那么简单快捷了。这不是说不可以进行与行之间的比较,而是说比较麻烦。这次讲解关联子查询或许可以改变你想法。

例题:假设一张表记录了每年的销售额。

 如何比较输出与上一年相比是增加或者减少的数据?

        首先可以尝试获取到与上一年销售额一致的是数据!

  1. -- 关联子查询:
  2. select s1.* from sales s1 where sale = (select sale from sales s2 where s1.year=s2.year-1)
  3. -- 外连接查询:
  4. select s1.* from sales s1 left join sales s2 on s1.sale = s2.sale where s1.year != s2.year

得到答案后进行一个处理后就可以拿到我们需要的结果!

  1. select s1.year , s1.sale ,
  2. CASE WHEN s1.sale > (select sale from sales s2 where s1.year -1 = s2.year ) then "上涨"
  3. WHEN s1.sale < (select sale from sales s2 where s1.year -1 = s2.year ) then "下降"
  4. ELSE "持平" END as var
  5. from sales s1 order by s1.year
  6. -- 或
  7. SELECT S1.year, S1.sale,
  8. CASE WHEN S1.sale = S2.sale THEN '→'
  9. WHEN S1.sale > S2.sale THEN '↑'
  10. WHEN S1.sale < S2.sale THEN '↓'
  11. ELSE ' — ' END AS var
  12. FROM Sales S1, Sales S2
  13. WHERE S2.year = S1.year - 1
  14. ORDER BY year;

但上面写的存在一个问题就当年份一旦出现空挡期那么就会造成数据错误!可以尝试使用比year小但是在小的当中最大值来进行处理。

  1. -- 自连接
  2. select s1.year,s1.sale from sales s1
  3. where s1.sale = (
  4. select s2.sale as sale from sales s2 where s2.year = (
  5. select max(s3.year)as year from sales s3 where s1.year > s3.year)
  6. )
  7. -- 连接查询
  8. select s1.year,s1.sale from sales s1 left join sales s2 on s1.sale = s2.sale
  9. where s2.year = (select max(s3.year) from sales s3 where s1.year > s3.year)

输出想要的结果可以使用CASE来进行

  1. SELECT S1.year, S1.sale,
  2. CASE WHEN sale =
  3. (SELECT sale
  4. FROM Sales S2
  5. WHERE S2.year = S1.year - 1) THEN '→' -- 持平
  6. WHEN sale >
  7. (SELECT sale
  8. FROM Sales S2
  9. WHERE S2.year = S1.year - 1) THEN '↑' -- 增长
  10. WHEN sale <
  11. (SELECT sale
  12. FROM Sales S2
  13. WHERE S2.year = S1.year - 1) THEN '↓' -- 减少
  14. ELSE '—' END AS var
  15. FROM Sales S1
  16. ORDER BY year;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/168774
推荐阅读
相关标签
  

闽ICP备14008679号