最近工作中需要用到查询语句结果为统计当前表和历史表加起来的数据之和需要把俩条数据的合加起来返回给我们:
select count() from work_order_history where valid = true and and state = ‘8’ and create_time like ‘%20230901%’;
返回结果如下

另一条SQL如下:
select count() from work_order where valid = true and and state = ‘8’ and create_time like ‘%20230901%’;
返回结果如下:

这里需要将0和1加起来,因为我的们的参数还要替换别的状态,这里展示的总数可能不明显
最后我们需要加起来的SQL为
select SUM(z.a) from (
select count() as a from select count() from work_order where valid = true and and state = ‘8’ and create_time like ‘%20230901%’ union all
select count() from work_order_history where valid = true and and state = ‘8’ and create_time like ‘%20230901%’
)z
SUM(z.a)这里如果查出来的结果想转换格式,我们可以换成cast(SUM(z.a) as CHAR)如下:
select cast(SUM(z.a) as CHAR) from (
select count() as a from select count() from work_order where valid = true and and state = ‘8’ and create_time like ‘%20230901%’ union all
select count() from work_order_history where valid = true and and state = ‘8’ and create_time like ‘%20230901%’
)z
博客围绕工作中MySQL查询需求展开,需统计当前表和历史表数据之和。给出两条查询语句,展示了将两条语句结果相加的SQL,还提及若要转换结果格式,可使用cast函数,如cast(SUM(z.a) as CHAR)。

3910

被折叠的 条评论
为什么被折叠?



