如何将两条sql的查询结果,横向合并成一个统计结果?

2024年11月18日 09:29
有3个网友回答
网友(1):

select ID,(select count(*) from 表A where ID='A') 货物总数,
(select count(*) from 表B where ID='A' and 是否抽查 is not null) 抽查数,
((select cast(count(*) as float) from 表B where ID='A' and 是否抽查 is not null)/(select cast(count(*) as float) from 表A where ID='A')) 抽查率
from 表A group by id;

网友(2):

WITH OK AS(SELECT ID,货物流水号,0 AS 是否抽查
FROM 表A
UNION ALL
SELECT ID,货物流水号, 是否抽查
FROM 表B)
SELECT ID,COUNT(DISTINCT 货物流水号) AS 货物总数,STR(SUM(是否抽查)*100/COUNT(DISTINCT 货物流水号),4,0)+'%'
FROM OK
GROUP BY ID

网友(3):

完全可以!~~~