2010-05-06 109 views
2

我有一个包含6个字段的表。这些列是ID,new_id价格,标题,Img,活动。我有价格列重复的数据。 当我做一个选择时,我想只显示不同的行,其中new_id不相同。 e.g.-消除SQL查询中的重复项

ID New_ID Price Title  Img Active 
1 1  20.00 PA-1  0X4... 1 
2 1  10.00 PA-10  0X4... 1 
3 3  20.00 PA-11  0X4... 1 
4 4  30.00 PA-5  0X4... 1 
5 9  20.00 PA-99A 0X4... 1 
6 3  50.00 PA-55  0X4... 1 

当select语句后,只有ID(1,4,9,6)行应该显示。原因是价格较高的new_ID应该显示出来。 我该怎么做?

在支持窗口聚集数据库
+1

ID 9没有一行吗? – 2010-05-06 23:49:36

+0

对不起,我的意思是1,4,5,6。最高价格和new_id只有一次 – ewdef 2010-05-06 23:55:16

+0

会有多少行?性能有多重要? – 2010-05-06 23:58:40

回答

2

(甲骨文,SQL Server 2005中的PostgreSQL 8.4)是这样的:

select id, new_id, price, title, img, active 
from (select id, new_id, price, title, img, active, 
      row_number() over (partition by new_id order by price desc) as position 
     from the_table 
) where position = 1 
0
select * 
from T as t 
where exists (select 1 from T where new_id = t.new_id 
group by new_id having max(price) = t.price) 

要测试存在,用exists!在这里,你想要基于new_id的最高价格的行。

我想只显示不同的行

通常,当有人想“重复行”,他们真正想要的“最新”的行或那些“最”的东西。它几乎总是可以以与上述类似的形式表达。

0
select * from ABC where charge_amt in(
SELECT  charge_amt 
FROM   ABC 
GROUP BY charge_amt 
HAVING  (COUNT(charge_amt) = 1)) 
order by charge_amt asc