首页 > 解决方案 > 通过自连接同一表进行计数,其中一个字段为空,但另一个字段具有值

问题描述

我有一张表,其中包含两组 GPS 坐标,一组由客户提供,另一组由我们的现场设备捕获。

表名为customer,字段名如下:

ID

纬度 [来自客户的数据]

经度 [来自客户的数据]

GPSLatitude [来自现场设备的数据]

GPSLongitude [来自现场设备的数据]

  1. 我想计算纬度和经度都是空白或包含值=0的所有此类
  2. 然后计算所有 GPSLatitude、GPSLongitude,其 ID 等于在 #1 中计数且不为空或不包含 value=0 的那些记录

标签: sqlsql-servercountcaseself-join

解决方案


我认为你想要条件聚合:

select count(*) cnt1, 
    sum(case when gpslatitude <> 0 and gpslongitude <> 0 then 1 else 0 end) cnt2
from customer 
where (latitude is null or latitude = 0)
  and (longitude is null or longitude = 0)

查询过滤客户经度和纬度null等于或等于0cnt1为您提供此类记录的计数。然后cnt2计算结果集中有多少条记录既不具有null也不具有设备坐标0


推荐阅读