2016-07-18 46 views
-1

此处我具有发票明细表。 我需要所有值不重复[invoiceno]。 我尝试DISTINCT不适用于MSSQL中的SELECT查询

select distinct invoiceno,name,addr1,addr2,id from invoice_table; 

结果:

invoiceno name    addr1  addr2    id 
2016718001 Severus Sanpe 7,Hogwards, Sevilee,USA 7451 5 
2016718002 Severus Sanpe 7,Hogwards, Sevilee,USA 7451 8 
2016718002 Severus Sanpe 7,Hogwards, Sevilee,USA 7451 9 

我想要的结果:

invoiceno name    addr1  addr2    id 
2016718001 Severus Sanpe 7,Hogwards, Sevilee,USA 7451 5 
2016718002 Severus Sanpe 7,Hogwards, Sevilee,USA 7451 8 

它在SELECT做工精细没有id。但我也需要这个。 如何做到这一点?

+0

看到ID,它是9项第3。 –

+0

id列是不同的,这是它出现两次的原因 – leetibbett

+0

“distinct”在整行上工作,因此它发生两次。该行是唯一的。 –

回答

3

你可能需要一组由MIN查询汇总功能:

select 
    invoiceno, name, addr1, addr2, min(id) as id 
from 
    invoice_table 
group by 
    invoiceno, name, addr1, addr2 

,或者如果同一张发票可以有多个名称和/或地址,你可以使用这样的事情:

select t.invoiceno, t.name, t.addr1, t.addr2, t.id 
from 
    invoice_table t inner join (select invoiceno, min(id) as min_id) m 
    on t.invoiceno=m.invoiceno and t.id=m.min_id 

这将返回每个invoiceno的第一个id(具有最低值的那个)。

+0

它工作正常......谢谢! –

+2

除了身份证以外,还有其他什么区别?这里需要另一个技巧。 –

3

如果你不想重复invoiceno,然后做一个典型的方法是使用row_number()

select iv.* 
from (select iv.*, row_number() over (partition by invoiceno order by id desc) as seqnum 
     from invoice_table iv 
    ) iv 
where seqnum = 1 ; 

你是误解如何select distinct作品。它适用于所有列(和表达式)在select列表中,包括id

+0

这工作很好... –

2

看来你只需要每张发票1个条目。 假设它是SQL Server 2008或更高

select * from (
select invoiceno,name,addr1,addr2,id, Row_number() over(partition by invoiceno order by invoiceno) RN from invoice_table 
) a where Rn=1 
+0

谢谢!它运作良好。 –

0

DISTINCT关键字适用于整个结果集:invoiceno,name,addr1,addr2,id。第2行和第3行在id字段上有所不同,因此它们将是不同的。

这有两种选择:

  1. 跳过ID
  2. 预过滤器ID-S与子查询

很明显,你可以跳过id字段是这样的:

select distinct invoiceno,name,addr1,addr2 from invoice_table; 

该分组有点棘手:

select invoiceno,name,addr1,addr2,id -- no distinct 
from invoice_table 
where id in (
    select min(id) from invoice_table 
    group by invoiceno -- we have this group by + min instead of the distinct keyword 
) 

第二个可能会对您的表现产生负面影响,所以请小心。

0

SELECT * FROM invoice_table其中ID IN(SELECT MIN(ID)FROM invoice_table
GROUP BY invoiceno,名称,ADDR1,ADDR2)