在SQL查询中需要您的帮助

时间:2012-10-25 13:07:24

标签: sql database

有两个表:

  • 客户id, name
  • 订单id, id_client, name),其中id_client - 外键。

编写一个查询,选择第一个表的标识符和名称以及与之关联的第二个表中的记录数。结果应按姓氏降序排序。

我试过

SELECT 
   Clients.id, Clients.name, count(id) 
FROM clients 
INNER JOIN Order ON Clients.id = Order.id_client 
GROUP BY 
   Clients.id, Clients.name 
ORDER BY 
   Clients.name DESC

但它不起作用。有什么问题?

4 个答案:

答案 0 :(得分:3)

SELECT
 c.ID,
 c.Name,
 COUNT(o.ID)
FROM
 Clients c
LEFT JOIN [Order] o
ON
 o.id_client = c.id
GROUP BY
 c.ID,
 c.Name
ORDER BY
 c.Name DESC

答案 1 :(得分:0)

SELECT Clients.id,Clients.name,count(client.id)FROM clients INNER JOIN Clients上的订单。= Order.id_client GROUP BY Clients.id,Clients.name ORDER BY Clients.name DESC

答案 2 :(得分:0)

count(id)更改为

count(Clients.id)count(Order.id)

我不知道你需要哪个表count(id)。我希望你能理解问题所在。

答案 3 :(得分:0)

SELECT
 c.ID,
 c.Name,
 COUNT(o.ID)
FROM
 Clients c,
 Order o
WHERE o.id_client = c.id
GROUP BY
 c.ID
 c.Name