Sql 如果属性存在,则为1,否则为0

Sql 如果属性存在,则为1,否则为0,sql,oracle,Sql,Oracle,在以下查询中,为1小时时间间隔内存在的每个属性输出1: select t1.attribute, count(*) from table1 t1 where timestamp >= trunc(sysdate-1/24, 'HH') and timestamp < trunc(sysdate, 'HH') and exists (select 1 from table2 t2 where t2.attribute = t1.attribute) group

在以下查询中,为1小时时间间隔内存在的每个属性输出1:

select t1.attribute, count(*)
from table1 t1
where timestamp >= trunc(sysdate-1/24, 'HH') and
      timestamp < trunc(sysdate, 'HH') and
      exists (select 1 from table2 t2 where t2.attribute = t1.attribute)
group by t1.attribute;

如何修改此选项,以便为不在时间间隔内的每个属性输出一个0?

在注释中,您声明表2具有完整的属性列表。如果是这种情况,请将表1左键连接到表2:

将左外部联接的时间戳筛选器从WHERE子句移到ON子句中,可以确保表1中的结果在执行左外部联接之前被截断。应用过滤器后,左侧外部联接将选择表2中的所有记录,并仅选择表1中匹配的记录


然后计算t1.attribute应该给你一个计数或者你想要的0。最后,在SELECT子句的t2.attribute上执行GROUPBY

选择所有行,并在[where time CONTECTIONS]1 else 0结束时创建一个案例,然后将其从where子句中删除?请提供一些样本数据,我想我不明白你们的问题。只有表2会有一个完整的属性列表,并没有时间戳。表1中的列表并非每小时都完整,因为某些属性在特定的小时内可能不“存在”。
select t2.attribute, count(t1.attribute)
from table2 t2
    LEFT OUTER JOIN table1 t1
        ON t2.attribute = t1.attribute 
        AND t1.timestamp >= trunc(sysdate-1/24, 'HH') 
        AND t1.timestamp < trunc(sysdate, 'HH')
group by t2.attribute;