sql - Oracle sql将每个第一个重复标记为true,其他标记为false
问题描述
作为 SQL oracle 的初学者,我正在处理一个CATS
包含 4 个 varchar2 字段country
、hair
和. 我正在尝试编辑一个 sql 请求,所以每次我点击一个新的元组时,如果我已经找到这个元组,我会添加一个属性,我会添加一个属性。color
firstItemFound
name || country || color
'true'
'false'
我想过这个:
步骤 1)更新(从猫中选择不同的名称、国家、颜色) tmp_cats set firstItemFound = true;
步骤 2)更新猫设置 firstItemFound = false 其中 firstItemFound 为空;
但是1)不起作用,因为您无法更新非物理视图。有什么解决办法吗?是否可以一次操作而不是两次操作?
这是我的表值(firstItemFound 列有空值):
NAME |COUNTRY |COLOR |
-------|----------|-------|
France |Shorthair |Red |
Brazil |Longhair |Yellow |
France |Shorthair |Red |
France |Longhair |Brown |
France |Longhair |Black |
Brazil |Longhair |Yellow |
Brazil |Longhair |Black |
Brazil |Longhair |Brown |
Brazil |Longhair |Yellow |
这是我想要的结果:
country hair color firstItemFound
---------------------------------------------
France Shorthair Red true
France Shorthair Red false
France Longhair Brown true
France Longhair Black true
Brazil Longhair Yellow true
Brazil Longhair Yellow false
Brazil Longhair Yellow false
Brazil Longhair Black true
Brazil Longhair Brown true
解决方案
你可以row_number
用来使第一项为真
select *,case when rn=1 then true else false end as firstItemFound from
(select country,hair,colur, row_number()
over(partition by country,hair,colur order by country) rn from t
) t
或者你可以使用 cte 表达式
with t as (
select * from
(
select 'France' as country ,'Shorthair' as hair,'Red' as colur from dual
union all
select 'Brazil','Longhair','Yellow' from dual
union all
select 'France' ,'Shorthair','Red' from dual
)
) , t2 as
(
select country,hair,colur, row_number()
over(partition by country,hair,colur order by country) rn from t
)select t2.*, case when rn=1 then 'true' else 'false' end as firstItemFound from t2
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=65146824ed31dbbc6daa40676220cdf8
COUNTRY HAIR COLUR RN FIRSTITEMFOUND
Brazil Longhair Yellow 1 true
France Shorthair Red 1 true
France Shorthair Red 2 false
推荐阅读
- node.js - 从数据库中获取分组项目
- c# - 将两个参数传递给 api 时出现 404
- wildfly - Wildfly 集群设置问题
- api - Kotlin - 设置缩放级别谷歌地图 Android Studio
- python - 如何使主题标签可点击并在 Django 的帖子中显示?
- python - 如何在不使用 sum 函数的情况下获得平均值
- javascript - Undefined 不是 React native 的对象 - 但之后会显示数据
- arrays - 从 Google 表格中的表格中删除一些列
- java - 在 Fragment 和 Activity 之间链接天气数据连接
- jupyter - Windows 10 更新:是什么导致我的分层建模代码运行缓慢而痛苦?