Sql 从结果中选择记录
我从一个查询中得到了以下数据 阿古诺 cld_类型_cd 来自 untl_dt 小时 00000080064 3. 2020-01-01 2020-01-01 5 00000080064 3. 2021-02-17 2021-02-17 1 00000080064 4. 2021-02-17 2021-02-17 无效的 00000080064 4. 2021-02-17 2021-02-17 2 00000080064 4. 2021-02-17 2021-02-17 1 )Sql 从结果中选择记录,sql,sql-server,select,Sql,Sql Server,Select,我从一个查询中得到了以下数据 阿古诺 cld_类型_cd 来自 untl_dt 小时 00000080064 3. 2020-01-01 2020-01-01 5 00000080064 3. 2021-02-17 2021-02-17 1 00000080064 4. 2021-02-17 2021-02-17 无效的 00000080064 4. 2021-02-17 2021-02-17 2 00000080064 4. 2021-02-17 2021-02-17 1 ) 根据您的数据样本
根据您的数据样本,您是否可以尝试上述查询,如果它适合您您可以使用窗口功能执行此操作:
select t.*
from (select t.*,
sum(case when cld_type_cd = 4 then 1 else 0 end) over (partition by agr_no, from_dt, untl_dt) as num_4s
from t
) t
where not (cld_type_cd = 3 and num_4s > 0);
此版本的优点是它只引用一次t
。因此,如果这是一个复杂的查询、CTE、视图或函数,那么它应该比多次引用它的解决方案更快
是DBFIDLE。您使用的是哪种DBMS产品?“SQL”只是所有关系数据库使用的查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加。
select t.*
from (select t.*,
sum(case when cld_type_cd = 4 then 1 else 0 end) over (partition by agr_no, from_dt, untl_dt) as num_4s
from t
) t
where not (cld_type_cd = 3 and num_4s > 0);