如何从这个SQL查询中获取第一个值

时间:2017-06-11 21:13:39

标签: mysql sql sql-server

我试图通过大多数订单获取客户的子查询clientId,但是当子查询未引入EXISTS时,只能在选择列表中指定一个表达式。

 SELECT a.ClientName 
FROM Clients as a 
INNER JOIN Orders as b 
    ON a.Id=b.ClientId 
WHERE b.ClientId 
 IN(SELECT b.ClientId,COUNT( b.ClientId) as MAKS FROM Orders as b 
    GROUP BY b.ClientId ORDER BY MAKS DESC)

我们是否有一些工具来处理这个问题?如何优化此查询?提前谢谢。

2 个答案:

答案 0 :(得分:0)

使用前1,计数和分组

SQL Server

SELECT Top 1 a.ClientName , count(b.orders_id) TotalOrders
FROM Clients as a 
INNER JOIN Orders as b 
    ON a.Id=b.ClientId 
GROUP BY a.client_name
order by TotalOrders desc

的MySQL

SELECT a.ClientName , count(b.orders_id) TotalOrders
FROM Clients as a 
INNER JOIN Orders as b 
    ON a.Id=b.ClientId 
GROUP BY a.client_name
order by TotalOrders desc
LIMIT 1

答案 1 :(得分:0)

你真的不需要内部联接,因为你要求两个表中的ID相同,

SELECT ClientName FROM Clients
WHERE Id = (SELECT TOP 1 ClientId FROM Orders 
GROUP BY ClientId
ORDER BY COUNT(ClientId) DESC)