pgsql 使用多表联合造成的count数据计算问题

之前看过相关资料知道在count的时候需要注意count字段中的null值

比如count(name),如果name有null,则不计入,所以大部分情况下我都用的count(1)或者count(*)

本次sql样例如下

SELECT 
    round(CAST(SUM(fcontractmoney) as numeric)/10000,2) AS money,count(1) as num,ta.contractType
FROM 
(
	select  'SG' as fcontracttype, '施工' as contractType
	union
	select  'JC', '监测' 
	union
	select  'SGJL', '施工监理' 
	union
	select  'KC', '勘察' 
	union
	select  'SJ', '设计' 
	union
	select  'KCSJJL', '勘察设计监理'
	union
	select  'ZJZX', '造价咨询' 
	union
	select  'ZBDL', '招标代理'
	union
	select  'SYJC', '试验检测'
	union
	select  'KCSJ', '勘察设计'
	union
	select  'QGCZX', '全过程咨询'
	union
	select  'HP', '环评'
	union
	select  'SB', '水保'
	union
	select  'QT', '其他'
) ta
left join
(
 select * from t_system_project as m, p_agreemen_contract_account as n 
 WHERE m.fid = n.fprojectid  and to_char(fsigntime,'YYYY')='2020'
  and n.fownerid = '030b197bd47542d6b6869166788b4d62'
  and m.fapp_id = '92154bbabd344156962e320a6927cac9'
  
) p on ta.fcontracttype = p.fcontracttype
GROUP BY ta.contractType

因为界面要显示固定的类型,但是数据里面可能暂时没有这么多类型

所以需要通过临时表进行关联

如果

select * from t_system_project as m, p_agreemen_contract_account as n 
 WHERE m.fid = n.fprojectid  and to_char(fsigntime,'YYYY')='2020'
  and n.fownerid = '030b197bd47542d6b6869166788b4d62'
  and m.fapp_id = '92154bbabd344156962e320a6927cac9

 可以查出所有的类型,则没问题

但是如果缺少某些类型,则对应类型统计结果为1

一开始没想到是临时表的问题

总是想会不会是count的问题,改为1,改为id统计都是一样的结果

最后发现,如果实际类型没有值,基与临时表总会统计一条数据,因为临时表这条数据是确定的

不能使用count(1)

最终的修改如下

SELECT 
    round(CAST(SUM(fcontractmoney) as numeric)/10000,2) AS money,count(p.*) as num,ta.contractType
FROM 
(
	select  'SG' as fcontracttype, '施工' as contractType
	union
	select  'JC', '监测' 
	union
	select  'SGJL', '施工监理' 
	union
	select  'KC', '勘察' 
	union
	select  'SJ', '设计' 
	union
	select  'KCSJJL', '勘察设计监理'
	union
	select  'ZJZX', '造价咨询' 
	union
	select  'ZBDL', '招标代理'
	union
	select  'SYJC', '试验检测'
	union
	select  'KCSJ', '勘察设计'
	union
	select  'QGCZX', '全过程咨询'
	union
	select  'HP', '环评'
	union
	select  'SB', '水保'
	union
	select  'QT', '其他'
) ta
left join
(
 select * from t_system_project as m, p_agreemen_contract_account as n 
 WHERE m.fid = n.fprojectid  and to_char(fsigntime,'YYYY')='2020'
  and n.fownerid = '030b197bd47542d6b6869166788b4d62'
  and m.fapp_id = '92154bbabd344156962e320a6927cac9'
  
) p on ta.fcontracttype = p.fcontracttype
GROUP BY ta.contractType

 

你可能感兴趣的:(pgsql 使用多表联合造成的count数据计算问题)