【问题标题】:SQL subquery exclude some elemSQL 子查询排除一些元素
【发布时间】:2018-04-10 21:08:33
【问题描述】:

我想返回类型为 6、类型为 7 或类型为 5 的元素。对于相同 register_document_id 的任何元素都不是类型 1 或类型 2。

注册文件:

id        register_document_id   type_document
0         10                      5
1         10                      6
2         10                      1
3         15                      6 
4         15                      7              
5         17                      5
6         18                      2
7         18                      1

在该示例中,我只想返回其 type_document 的值为 6、7 或 5 按 register_document_id 分组的行。通过相同的 register_document_id 我想排除具有类型 2 和 1 的那些。

输出查询:

  register_document_id     type_Document
         15                     6
         15                     7
         17                     5




select x.register_document_id,x.type_document
from register_document x
where x.type_document= 6 or x.type_document = 7 or x.type_document = 5 AND NOT EXISTS (
    SELECT *
    FROM register y
    WHERE y.number_id = x.number_document AND (y.type_document <> '1' <> y.type_document <> '2'
   )
 group by x.register_document_id,x.type_document;

【问题讨论】:

  • 在不涉及聚合函数的情况下为什么要使用 GROUP BY?
  • 不明确的 OP...return the elements that have the type 6, or the type 7, or the type 2 ... And any of them for the same register_document_id hasn't the type 1 or 2. .........类型 2 不明确

标签: sql select subquery


【解决方案1】:

你需要in!查询应如下所示:

select rd.register_document_id, rd.type_document
from register_document rd
where rd.type_document in (5, 6, 7) and
      not exists (select 1
                  from register_document rd2
                  where rd2.number_id = rd.number_document and
                        rd2.type_document in (1, 2)
                 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多