oracle - 在sql中做减号时只考虑特定的列
问题描述
我有一个包含列的“设备”表 - id、组、函数、日期。函数可以有两个值——“打印”、“复制”和“扫描”。组可以有值 - A、B、C.... 我想运行查询 select distinct id, group, date from device where function = 'print' minus (select id, group, date where function in ('copy' , 'scan') 按日期排序;
在这里,我想要一个仅用于打印特定组的设备的设备 ID 列表。如果我们有这个设备表:
设备:
id group function date
1 a print 26-06-20
1 a scan 27-06-20
2 a print 28-06-20
2 b scan 29-06-20
3 a print 30-06-20
在这种情况下,我希望结果为 {(2, a, 28-06-20), (3, a, 30-06-20)} 在这里我不想要 device_id 1 因为它具有两个值 'print ' 并扫描同一组。我只想要那些除了 print 之外没有其他值的设备 ID 用于同一组。这里的设备 id 也有两个值 - 'print' 和 'scan' 但它们用于不同的组。打印用于 a 组,扫描用于 b 组。所以对于设备 id - 2 和组 - 'a' 我们只有打印。所以我想在我的设备列表中有 device_id 。对于设备 ID - '3' 在函数表中只有打印值,所以我也希望它出现在我的列表中。
我面临的问题是查询没有按预期工作,因为打印和扫描设备 ID 的日期不同,即使它们属于同一组。因此,当我尝试做减号时,我还会得到那些同时具有同一组的值“打印”和“扫描”的设备 ID,因为由于日期不匹配而没有发生减号。我想知道在查询中做减号时如何忽略日期?
我正在使用的查询 - 从设备中选择不同的 id、组、日期 where function = 'print' minus (select id, group, date where function in ('copy', 'scan') order by date;
解决方案
您可以使用NOT EXISTS
如下:
select distinct workstation_id, type, usage_date
from device d
where d.type = 'print'
and not exists (select 1
from device dd
where dd.workstation_id = d.workstation_id
and dd.group = d.group
and dd.type = 'scan');
建议:永远不要使用NOT IN
推荐阅读
- javascript - 变异后如何强制App重新渲染?
- django - Django 测试用例中的线程没有关闭数据库连接
- laravel - 将我的 laravel 项目命名为 crm 有什么问题吗
- python - 检查夹具是否被执行
- entity-framework - EF6 与 SQLite - 不恢复列表
- date - SAS:将 date_from 和 date_to 分隔成单独的行
- php - 用于将 BEM 字符串拆分为多个部分的正则表达式模式 (PHP)
- sql-server - SonarQube docker 镜像在 App Service ACI 下运行不成功
- java - 将 Spring Boot 1.5.8 迁移到 2.1.5 -- Gradle 问题
- javascript - amCharts:禁用 Legend 中某些项目的切换