【问题标题】:SQL query function to find out - [closed]SQL查询功能找出来 - [关闭]
【发布时间】:2020-10-30 18:43:57
【问题描述】:

我的桌子是这样的

A    B
1    20
1    30
2    20
3    50
4    20
4    30
4    50

我正在编写一个传递参数2030 的函数,然后我必须从A 列中找出值,该值恰好具有来自B 列的值2030。在这种情况下@应返回 987654327@。 4 不应返回,因为它也有 50

【问题讨论】:

  • MySQL 还是 Postgres?请仅标记一个数据库。

标签: mysql sql postgresql


【解决方案1】:

这是一个使用group byhaving 的便携式选项:

select a
from mytable
group by a
having 
    sum(case when b in (20, 30) then 1 else 0 end) = 2
    and sum(case when b not in (20, 30) then 1 else 0 end) = 0

这假定没有重复 (a, b)。否则:

having max(case when b = 20 then 1 else 0 end) = 1
   and max(case when b = 30 then 1 else 0 end) = 1
   and max(case when b not in (20, 30) then 1 else 0 end) = 0

如果你在运行 Postgres,我们可以使用数组:

having array_agg(b order by b) = array[10, 20]

在 MySQL 中,我们可以使用字符串聚合:

having group_concat(b order by b) = '10,20'

【讨论】:

  • 我们怎样才能让它更有活力?参考您的第一个回复。就像-假设我在函数中传递数组,而不是两个数字2030,我们如何检查呢? @GMB
  • @Shashank:答案演示了如何使用 Postgres 数组执行此操作:having array_agg(b order by b) = array[10, 20]
  • 我们如何在函数中传递数组作为参数? @GMB
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多