zoukankan      html  css  js  c++  java
  • 关于sql别名无法直接运算,行求和的问题

    今天工作的时候遇到了一个问题,就是用case when 取别名时无法运算,会报错

    举例说明下,现在有一张订单表,表里数据如下:

    状态01,02,03分别代表待付款,已付款,退款,现在需求为统计各个商品待付款,已付款,退款的数量

    sql如下:

    select goods,count(case when goodstatus=01 then 1 else null end) dfk,

    count(case when goodstatus=02 then 1 else null end) yfk,

    count(case when goodstatus=03 then 1 else null end) tk from goodsorder group by goods

    结果如下:

    现在我们想统计每样商品各种状态的订单一共多少笔,看着很简单,直接sum相加就可以了,实际上sql中别名不能参与运算,最后我用子查询重新查了一遍才可以,语句如下

    select goods,dfk,yfk,tk,(dfk+yfk+tk) total from
    (select goods,count(case when goodstatus=01 then 1 else null end) dfk,
    count(case when goodstatus=02 then 1 else null end) yfk,
    count(case when goodstatus=03 then 1 else null end) tk
    from goodsorder group by goods) as aa

    结果如下:

  • 相关阅读:
    2-分类
    1-确定变量间是否有关系—显著性检验
    git简单操作
    Hadoop HA和Hbase HA
    Docker入门操作
    内存数据库专题(MemCached 和Redis)
    Spark MLlib和Sprk GraphX
    Spark 调优
    Spark Streaming基础
    Spark SQL
  • 原文地址:https://www.cnblogs.com/xiuyu/p/10582233.html
Copyright © 2011-2022 走看看