我有一个 SQL 查询,它计算表中的项目数并按省名对它们进行分组。我有另一个要加入的表,其中有一列用于上传,仅显示已上传的项目。我想从减去两列中得到待处理的项目。
这是我的数据
totallabs LabUploaded 147 0 150 0 156 0 273 0 176 0 244 1 38 1 131 0 197 1 133 1 124 0
这就是我们要达到的目标
totallabs LabUploaded Pending 147 0 147 150 0 150 156 0 156 273 0 273 176 0 176 244 1 243 38 1 37 131 0 131 197 1 196 133 1 132 124 0 124
这是我对第一个表的查询
select count(l.facility_name) as totallabs, count(u.lab_code) as LabUploaded from labs l left join upload u on u.lab_code = l.mfl_code inner join province p on p.id = l.province_code group by p.province_name
我试图用SubQueryAlias给我数据但没有得到正确的数据,
SubQueryAlias
select SubQueryAlias.* , totallabs - LabUploaded as pending from ( select ( select count(l.facility_name) from labs l ) as totallabs, ( select count(u.lab_code) from upload u ) as LabUploaded from labs l left join upload u on u.lab_code = l.mfl_code inner join districts p on p.id = l.district_code group by p.district_name ) as SubQueryAlias
如何在两个计数列之间减去并获取待处理的数据。任何帮助表示赞赏
下次,请提供一些示例数据和表格,您可以使用 SQL Fiddle 使其更容易。
检查这是否适合您的需求:
SELECT province_code, COUNT(labs.mfl_code) TotalLabs, COUNT(uploads.lab_code) Uploads, COUNT(labs.mfl_code) - COUNT(uploads.lab_code) Pending FROM labs LEFT join uploads ON uploads.lab_code = labs.mfl_code GROUP BY province_code SQl 小提琴示例: http ://sqlfiddle.com/#!9/c689e7/1
如果您发现我的回答有用,如果您投票并标记为已接受,我将不胜感激。