【问题标题】:SQL Select one value but take in account other values as wellSQL 选择一个值但同时考虑其他值
【发布时间】:2020-11-29 23:16:44
【问题描述】:

这就是表格的样子

Number   UniqID   status
555      1        in
555      1        in
555      1        in
555      2        in
555      2        out
555      2        in

我想这样选择

Number   UniqID   status
555      1        in
555      1        in
555      1        in

并且只有在 all 相同的 uniqID 具有状态时才选择它。如果其中一个状态表明相同的 ID 跳过整个事情。 UniqID 也是自动生成的

并想像这样显示它

Number    status
555       in

【问题讨论】:

标签: mysql sql subquery aggregate-functions where-clause


【解决方案1】:

您可以使用not exists 获得第一个结果集:

select *
from mytable t
where 
    t.status = 'in' 
    and not exists (
        select 1 
        from mytable t1 
        where t1.number = t.number and t1.uniqid = t.uniqid and t1.status = 'out'
    )

另一方面,如果您想要所有状态都为“in”的所有(number, uniqid) 元组,聚合更简单:

select number, uniqid, min(status) as status
from mytable
group by number, uniqid
having min(status) = max(status) and min(status) = 'in'

【讨论】:

  • 您好,感谢您的快速回复。但是如果不知道唯一 ID 怎么办,它是随机生成的,我仍然想获取所有 uniqID 状态为“in”的“数字”,如果其中一个“out”,则跳过整个事情
  • @BornToLive:上面的查询不会对unqid 进行任何硬编码,所以它们应该做你想做的事情(它们会返回你为样本数据显示的结果)。请注意,名为 uniqid 的东西实际上在表中并不是唯一的(如您的示例数据所示),这是相当违反直觉的。
  • 知道了,成功了,谢谢。只是有另一个问题,如何在最终结果中只得到一个 555 而不是同一条目的 3 个
  • 别着急,已经弄明白了,再次感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 2016-06-15
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多