SQL查询以查找最高价格购买的名称?

时间:2015-11-01 19:14:57

标签: sql oracle

我有两个表,customerspurchasesPurchasestotal_price列,外键cid引用customers.cid。我需要选择购买总价最高的客户(来)的名字。

我正在尝试这个

select 
    cname 
from 
    customers c 
where exists
    (select pid 
     from purchases p 
     where total_price in (select max(total_price) 
                           from purchases p 
                           where max(total_price) = total_price 
                             and p.cid = c.cid))

我收到错误,此处不允许使用群组功能 - >

where max(total_price) = total_price

请帮帮我

4 个答案:

答案 0 :(得分:1)

您可以总结每位客户的总数,然后按最高总数排序:

select cname, sum(total_price) as totals
from customers c
inner join purchases p
  on c.cid = p.cid
group by cname
order by totals desc
limit 1

以下是MySQL数据库的示例:http://sqlfiddle.com/#!9/133fa/1

我在这里有一个Oracle示例:http://sqlfiddle.com/#!4/9d786/4

with 
totals as
(
  select cid, sum(total_price) as totals
  from purchases
  group by cid
), 
highest as (
  select max(totals) as highest from totals
)
select cname
from customers c
inner join totals t on c.cid = t.cid
inner join highest h on t.totals = h.highest

答案 1 :(得分:1)

您还可以在临时表中存储每位客户的最高购买量(例如,在SQL Server中):

int

之后,您可以选择total_price最高的客户:

SELECT c.cid, cname, max(total_price) as total
into #temp_customers_highest_purchase
FROM customers c
JOIN purchases p on c.cid = p.cid
group by c.cid, cname

由于您没有使用子查询,因此这种方法可能具有性能。

如果您不使用SQL Server,可以尝试使用WITH clausule,这对性能非常有帮助。

select cname, total 
from #temp_customers_highest_purchase tmp
join customer c on c.cid = tmp.cid

答案 2 :(得分:0)

要选择前10名“total_price”的名称,请输入(假设您使用的是Microsoft SQL Server - 其他SQL服务器提供与“top”类似的功能):

SELECT TOP 10 cname FROM customers c
INNER JOIN purchases p on c.cid = p.cid
order by p.total_price DESC

将“10”替换为您想要的任何数字,如果您有大量数据,请注意在连接和订购列上添加索引...

如果您有超过10个客户使用相同的total_price,您将无法看到所有这些客户。

-----------编辑:要查看所有客户端,而不是客户端具有最高total_price(但如果他有两次购买具有相同[最高] total_price,则不会复制一个客户端: -----------

SELECT DISTINCT cname FROM customers c
INNER JOIN purchases p ON c.cid = p.cid
WHERE p.total_price =
(SELECT MAX( p2.total_price ) FROM purchases p2)

答案 3 :(得分:0)

select 
    Name, 
    (select sum(total_price) from purchases where cid=customers.cid) as HighestTotalPrice 
from 
    customers