使用DISTINCT名称SQL SERVER选择TOP 2

时间:2014-06-25 00:23:12

标签: sql sql-server select distinct distinct-values

我需要获得花费更多资金但不重复的前2名客户。

我有这段代码:

Select DISTINCT Top 2 Clientes.Nome, Clientes.NCartao, Vendas.ValorCIva 
from Clientes AS Cli, Vendas
INNER JOIN Clientes ON Clientes.IdCliente = Vendas.IdCliente
order by Vendas.ValorCIva DESC

我有这个结果:

Client          Number  Total
José Pinto      123456  8,48
José Pinto      123456  6,52
Joao Ferreira   564789  5,75

但我想要这个:

Client          Number  Total
José Pinto      123456   15
Joao Ferreira   564789  5,75

2 个答案:

答案 0 :(得分:4)

一种方法:

select Top 2 Clientes.Nome, Clientes.NCartao, sum(Vendas.ValorCIva) ValorCIva 
from Clientes AS Cli, Vendas INNER JOIN Clientes ON Clientes.IdCliente = Vendas.IdCliente 
group by Clientes.Nome, Clientes.NCartao
order by sum(Vendas.ValorCIva) DESC

答案 1 :(得分:0)

如果你不想重复那个客户端放置一个GROUP BY,那么它会自动显示每个客户端而不会重复,就像这样......

Select Top 2 Clientes.Nome, Clientes.NCartao, Vendas.ValorCIva 
FROM Clientes AS Cli, Vendas
INNER JOIN Clientes ON Clientes.IdCliente = Vendas.IdCliente
GROUP BY Clientes.Nome
ORDER BY Clientes.Nome