只获取同一个名称,索引,数量但代码不同的一行

时间:2012-01-09 14:20:23

标签: sql select distinct

我收到了查询:

select distinct index, name, code, amount as amount_min 
from sales s 
where (amount = 
(
    select mindex(s1.amount) 
    from sales s1 
    where  s1.name = s.name
)) 
order by s.name

查询工作得很好,但我想修改它们,以便当列索引,代码,数行中的数量相同时,只有一个显示,第一行。其余的(虽然不同的代码列)应该被忽略。有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

由于我不知道它是oracle,sql server,sybase ase等,你这样做是这样的:

步骤1:将数据插入带有标识列的临时表

select distinct counter = identity(10), index, name, code, amount as amount_min
into #t1
from sales s 
where (amount = 
(
    select mindex(s1.amount) 
    from sales s1 
    where  s1.name = s.name
)) 
order by s.name

第2步:进行必要的选择

select index, name, code, amount_min from #t1
where counter in (select min(counter) from #t1 group by index, name, amount_min)

第3步:删除临时表

drop table #t1