Oracle 在SQL中做减法时只考虑特定列
我有一个“设备”表,其中有列-id、组、函数、日期。函数可以有两个值-“打印”、“复制”和“扫描”。组可以有值-A、B、C。。。。 我想运行查询selectdistincidid,group,datefromthedevicewhere function='print'减去selectid,group,datewhere function in'copy','scan'orderbydate 这里我想要一个设备ID列表,这些设备只用于打印特定组。 如果我们有此设备表: 设备:Oracle 在SQL中做减法时只考虑特定列,oracle,oracle-sqldeveloper,Oracle,Oracle Sqldeveloper,我有一个“设备”表,其中有列-id、组、函数、日期。函数可以有两个值-“打印”、“复制”和“扫描”。组可以有值-A、B、C。。。。 我想运行查询selectdistincidid,group,datefromthedevicewhere function='print'减去selectid,group,datewhere function in'copy','scan'orderbydate 这里我想要一个设备ID列表,这些设备只用于打印特定组。 如果我们有此设备表: 设备: id gr
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}
在这里,我不想要设备_id 1,因为它具有相同组的“打印”和“扫描”值。我只希望同一组的设备ID没有打印以外的值。
这里设备id也有两个值-“打印”和“扫描”,但它们用于不同的组。打印用于a组,扫描用于b组。因此,对于设备id-2和组-a,我们只有打印。因此,我希望在设备列表中包含设备id。
对于设备id-“3”在函数表中只有打印值,因此我也希望它在我的列表中
我面临的问题是,查询没有按预期工作,因为打印和扫描设备ID的日期不相同,即使它们属于同一组。因此,当我尝试做减号时,我也会得到那些设备ID,它们的值为同一组的“print”和“scan”,因为减号不是由于日期不匹配而发生的。我想知道如何在查询中执行减号时忽略日期
我正在使用的查询-从设备中选择不同的id、组、日期,其中函数为'print',减去选择id、组、日期,其中函数为'copy','scan'按日期排序 请使用下面的查询
select distinct workstation_id, type, usage_date from device where type =
'print' and id not in (select id from device group by id having count(1) > 1 );
select distinct workstation_id, type, usage_date from device where type =
'print' and id not in (select id from
(select id, count(1) from group by id having count(1) > 1) qry);
您也可以使用下面的查询
select distinct workstation_id, type, usage_date from device where type =
'print' and id not in (select id from device group by id having count(1) > 1 );
select distinct workstation_id, type, usage_date from device where type =
'print' and id not in (select id from
(select id, count(1) from group by id having count(1) > 1) qry);
您可以使用“不存在”选项,如下所示:
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,您只需删除id where type!='打印'
select distinct workstation_id, type, usage_date from device
where type = 'print' and workstation_id not in (select workstation_id from device where type != 'print');
问题更新后
select distinct id, group, date from device d1
where function = 'print' and not exists (select 1 from device d1
where
function != 'print' and d1.id=d2.id and d1.group=d2.group);
仅用于打印特定组的设备的设备ID列表
结果:
ID group FUNCTION date(YYYY-MM-DD)
2 a print 2020-06-28
3 a print 2020-06-30
我希望您的示例数据使用虚构的示例列名。在编写查询时,使用诸如GROUP或DATE之类的SQL关键字作为列名会导致语法错误。每个试图测试此问题答案的人都必须更改列名或使用带双引号的标识符。您使用的是哪种数据库?一旦您确定了使用的是哪种RDBMS,请永远不要看?为什么不呢?我已经更新了问题。你能根据我更新的问题回答吗?如果没有空,NOT IN将无法正常工作。答案将根据更新后的要求进行更新。请现在检查@Tejash你现在能查一下这个问题吗?我稍微修改了一下……所以这个解决方案不起作用。没错,@Tejash。但这不是不使用它的理由。如果你说当心空值或类似的东西,那就更有意义了。“永不”这个词可能太强了。我已经更新了这个问题。你能根据我更新的问题回答吗?我已经更新了问题。你能根据我最新的问题回答吗?