【问题标题】:How to manage COUNT, GROUP BY and HAVING?如何管理 COUNT、GROUP BY 和 HAVING?
【发布时间】:2021-01-28 15:55:42
【问题描述】:

我没有尝试过 SQL,我可能会尝试做一些不可能的事情。 SQL 给人这种感觉,只需要 1 个请求就可以做到,但也许不是......

我有 4 个连接表 A -> S -> T -> F。 一个简单的请求给我这些数据:

select a.id, s.id, t.type, f.name
from table_a a
    inner join table_s s on a.id = s.id
    inner join table_t t on t.id = s.t_id
    inner join table_f f on f.id = t.f_id
where f.name = 'C';

a.id | s.id | t.type | f.name
-----------------------------
1    | 1    | E      | C
1    | 2    | R      | C
2    | 3    | E      | C
3    | 4    | R      | C

我想找到关联多个 S 行的所有 A id。 我想找到所有只有一个 S 行 T 类型 = R 的 id。

对于第一个,我做了这个 SQL 查询:

select a.id from table_a a
    inner join table_s s on a.id = s.id
    inner join table_t t on t.id = s.t_id
    inner join table_f f on f.id = t.f_id
where f.name = 'C'
group by a.id
having count(s.*) > 1;

但是现在,对于第二个查询,我不明白如何过滤 t.type 和 count。 我尝试了这个请求,但是响应不好(返回a.id = 1)

select a.id from table_a a
    inner join table_s s on a.id = s.id
    inner join table_t t on t.id = s.t_id
    inner join table_f f on f.id = t.f_id
where f.name = 'C'
group by a.id
having count(s.*) = 1 and t.type = 'R';

有什么想法吗? 谢谢

【问题讨论】:

  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)的 SQL,并以表格格式作为代码输入。 How to Ask 暂停总体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你期望的内容和原因。

标签: sql postgresql count inner-join having-clause


【解决方案1】:

我想找到所有只有一个 S 行 T 类型 = R 的 id。

这是你想要的吗?

select a.id from table_a a
    inner join table_s s on a.id = s.id
    inner join table_t t on t.id = s.t_id
    inner join table_f f on f.id = t.f_id
where f.name = 'C' 
group by a.id
having count(*) = 1 and min(t.type) = 'R'

这为您提供了只有一行的组,其类型为“R”。

【讨论】:

  • 是的,它似乎工作,谢谢。但是我真的不明白MIN的使用。我很难理解 HAVING 的使用...我在想 HAVING 是在 GROUP BY 之后过滤结果。好的 count(s.*) = 1 是分组前的数据,但 MIN 对我来说完全是魔法:)
  • @MychaL:因为组中只有一行(这就是having 子句的作用),所以min() 为您提供组中可用的(唯一)值。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 2016-10-11
  • 1970-01-01
相关资源
最近更新 更多