【问题标题】:Not the right subquery, multple counties in a state trying to get count of state不是正确的子查询,一个州的多个县试图获得州的计数
【发布时间】:2015-09-02 15:56:40
【问题描述】:
SDRP15_COSD table
   | ST_code |      |SD Code|     |County Code|

     04                123            001
     06                232            001
     09                332            001


Submission table
| ST_code |         |SD_Code|         |Date|

     04                123            01/21/2003
     06                232            null
     09                332            01/21/2003

我尝试过这种方式,但我认为它不符合我的要求。

select st_code, count(sd_code)
from sdrp15_cosd
where sd_code in 
(select sd_code from submission_table
where date is null)
group by st_code
order by st_code

这里的要求是日期字段为空的相应州的提交表中列出的每个县的总数。考虑到一个州有多个县。与我的 1000 行相比,这些表是简化版。

【问题讨论】:

  • 为什么是子查询而不是联接?除此之外,你为什么不认为它满足要求——你期望什么结果,你会得到什么?
  • 一个县似乎有多个州,反之亦然。
  • @AlexPoole 我想得到 3 个字符的数字,显然我简化了这些行,因为这里有 100 行数据会过于庞大......我的同事给了我一个提示并告诉我我使用子查询。但是如果它是一个连接条件,我会从哪里开始。

标签: sql oracle


【解决方案1】:

我想我明白了。你需要做的是通过st码和sd码加入表格,然后简单地使用where date is null并按县码分组。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    这个查询会给你想要的结果,我假设几件事 st_code 和 sd_code 对于特定国家/地区是唯一的。

    select count(1),country 
    from ex_9 a,ex_10 b 
    where a.st_code = b.st_code 
    and a.sd_code = b.sd_code 
    and b.data is null 
    group by country
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-24
      • 2017-10-27
      • 2021-03-14
      • 2012-10-17
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多