当前位置:   article > 正文

PostgreSQL的case when语句使用_postgresql case when

postgresql case when
  1. case when语句第一种方式:
  2. case
  3. when 表达式1 then 结果1
  4. when 表达式2 then 结果2
  5. else 结果n
  6. end
  7. 举例1
  8. select sum(
  9. case
  10. when rental_rate=0.99 then 1
  11. else 0
  12. end
  13. ) as "aa",
  14. sum(
  15. case
  16. when rental_rate=2.99 then 1
  17. else 0
  18. end
  19. ) as "bb",
  20. sum(
  21. case
  22. when rental_rate=4.99 then 1
  23. else 0
  24. end
  25. ) as "cc"
  26. from film;
  27. 结果:
  28. aa bb cc
  29. 341 323 336
  30. 【注】:as后接的别名需要带双引号,否则报语法错误
  31. case when语句第二种方式:
  32. case 表达式
  33. when 匹配1 then 结果1
  34. when 匹配2 then 结果2
  35. else 结果n
  36. end
  37. 举例2
  38. select sum(
  39. case rental_rate
  40. when 0.99 then 1
  41. else 0
  42. end
  43. ) as "aa",
  44. sum(
  45. case rental_rate
  46. when 2.99 then 1
  47. else 0
  48. end
  49. ) as "bb",
  50. sum(
  51. case rental_rate
  52. when 4.99 then 1
  53. else 0
  54. end
  55. ) as "cc"
  56. from film;
  57. 结果:
  58. aa bb cc
  59. 341 323 336

上面是在网上搜到的介绍

下面是自己实际用到的情况,供自己学习记录。

  1. SELECT c.unit,
  2. case when d.money ::DECIMAL = 0.00
  3. then '0%'
  4. else concat(round(c.number ::DECIMAL/d.money ::DECIMAL*100,2),'%') end as rate
  5. FROM (
  6. SELECT p.unit,sum(p.number::DECIMAL) as number FROM table p
  7. WHERE p.code IN (SELECT code FROM code_table )
  8. GROUP BY p.unit
  9. ) c
  10. left join (
  11. SELECT unit,sum(money::DECIMAL) as money FROM code_table
  12. GROUP BY unit
  13. ) d
  14. on c.unit = d.unit

使用时case when then 的数据类型要相同,否则会报错

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

闽ICP备14008679号