【问题标题】:Count by Self Joining same table where one field is empty but another has value通过自连接同一表进行计数,其中一个字段为空但另一个字段具有值
【发布时间】:2021-01-09 02:05:21
【问题描述】:

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

表名为customer,字段名如下:

身份证

纬度 [来自客户的数据]

经度 [来自客户的数据]

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

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

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

【问题讨论】:

  • 请向我们展示您的尝试。
  • 样本数据和期望的结果会有所帮助。例如,id 是唯一的吗?
  • @GordonLinoff ID 是唯一的。
  • @DaleK 我用 case 语句进行了求和,并尝试自行加入不起作用的表。不幸的是,我以为我保存在服务器上的查询没有正确保存。
  • @DaleK 这是我尝试过的查询: SELECT sum(CASE WHEN C.lat = '' THEN 1 ELSE 0 END) count_nulls, sum(CASE WHEN CD.GPSLatitude '' THEN 1 ELSE 0 END) count_not_nulls FROM Customer C (Nolock) Left Join customer cd (nolock) on Cd.CustomerId=c.CustomerId

标签: sql sql-server count case self-join


【解决方案1】:

我想你想要条件聚合:

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 或等于0 的客户经度和纬度。 cnt1 为您提供此类记录的计数。然后cnt2 计算结果集中有多少条记录既没有null 也没有0

【讨论】:

  • 谢谢@GMB,这是解决方案,我错误地尝试进行自联接,而简单的 where 子句可以像您的解决方案一样完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多