mysql中SQL语句查询字段相加的和,以及更改小数精确位。和查询SQL语句结果相减的SQL查询

最近在工作中碰到了SQL进行查询,用户缴费以及退费信息的工作,以及查询完后需要修改SQL结果后小数位的需求,整理结果如下:
首先,看内容:
mysql中SQL语句查询字段相加的和,以及更改小数精确位。和查询SQL语句结果相减的SQL查询_第1张图片

如图,operate_type代表缴费与退费,分别用0和1区别。

##需求1:查询所有缴费数据之和:
select
SUM(pay_data)
from
xxx(表名)
where
and operate_type =0
and order_time between ‘2023-05-12 14:46:02’ and ‘2023-06-12 14:46:02’;
查询结果为5823.0
这里如果我们需要修改SQL查询结果的小数位精度的话,修改后SQL如下:
select
cast(SUM(pay_data) AS decimal(10,2))
from
xxx(表名)
where
and operate_type =0
and order_time between ‘2023-05-12 14:46:02’ and ‘2023-06-12 14:46:02’
查询结果为5823.00
##需求2:查询所有退费数据之和:
select
SUM(pay_data)
from
xxx(表名)
where
and operate_type =1
and order_time between ‘2023-05-12 14:46:02’ and ‘2023-06-12 14:46:02’;
查询结果为7.0
这里如果我们需要修改SQL查询结果的小数位精度的话,修改后SQL如下:
select
cast(SUM(pay_data) AS decimal(10,2))
from
xxx(表名)
where
and operate_type =1
and order_time between ‘2023-05-12 14:46:02’ and ‘2023-06-12 14:46:02’
查询结果为7.00
## 需求3:查询所有缴费和退费数据(缴费数据-退费数据):

select
       (
              select
                     SUM(pay_data)
              from
                     xxx(表名)
              where
                     and operate_type =0
                     and order_time between '2023-05-12 15:30:35' and '2023-06-12 15:30:35'
       )
       -
       (
              select
                     SUM(pay_data)
              from
                     xxx(表名)
              where
                     and operate_type =1
                     and order_time between '2023-05-12 15:30:35' and '2023-06-12 15:30:35'
       );
       上面用到的俩条SQL语句可以直接进行相减。然后select查询
       **这里如果我们需要修改SQL查询结果的小数位精度的话,修改后SQL如下:**
       select
   cast(SUM(
             (
                    select
                           SUM(pay_data)
                    from
                           xxx(表名)
                    where
                           and operate_type =0
                           and order_time between '2023-05-12 10:36:29' and '2023-06-12 10:36:29'
            )
            -
            (
                   select
                          SUM(pay_data)
                   from
                          xxx(表名)
                   where
                          and operate_type =1
                          and order_time between '2023-05-12 10:36:29' and '2023-06-12 10:36:29'
            )
            ) as decimal(10,2))

你可能感兴趣的:(mysql,sql,java)