Oracle SQL如何消除按特定列重复的行

问题描述 投票:0回答:2

例如,我在一张表中具有如下所示的值

 Table A                          
 ----------------                 
 item_name price departure        
 ----------------                 
 shoe      10    150
 shoe      10    150              
 socks     2     100              
 socks     2     110
 shirt     5     170
 shirt     5     170            
 gloves    1     210  
 gloves    1     210
 gloves    1     210    

我想选择所有具有唯一item_name的行,所以简单的方法是使用UNION

select item_name, price, departure from table A
UNION 
select item_name, price, departure from table A

但是就像你看到袜子有不同的方向,我的结果是错误的,因为我得到了结果

 Table A                          
 ----------------                 
 item_name price departure        
 ----------------                 
 shoe      10    150             
 socks     2     100              
 socks     2     110
 shirt     5     170          
 gloves    1     210  

您能帮我吗,我在寻找简单的方法而不需要左联接,因为表A包含很多数据,并且我想优化

我想获得以下结果,其中袜子的部门相同(项目名称和价格)最小”

Table A                          
 ----------------                 
 item_name price departure        
 ----------------                 
 shoe      10    150             
 socks     2     100              
 shirt     5     170          
 gloves    1     210  

感谢帮助

sql oracle group-by greatest-n-per-group
2个回答
0
投票

使用row_number()是从表中选择特定行的有效方法。在over()子句中,使用partition byorder by控制何时将行号重置为1:

select
    *
from (
    select
         item_name
       , price
       , departure
       , row_number() over(partition by  item_name order by price, departure) as rn
    from mytable a  
    ) d
where rn = 1
ITEM_NAME |价格|出发RN:-------- | ----:| --------:| -:手套| 1 | 210 | 1个衬衫5 | 170 | 1个鞋| 10 | 150 | 1个袜子| 2 | 100 | 1个

db <>小提琴here


1
投票

我认为您只需要聚合:

select item_name, price, min(departure) departure
from mytable
group by item_name, price

Demo on DB Fiddle

ITEM_NAME |价格|离开:-------- | ----:| --------:鞋| 10 | 150袜子| 2 | 100衬衫5 | 170手套| 1 | 210
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.