来自多个表的数据并在select中使用count()

时间:2012-03-03 02:25:51

标签: sql-server-2008 join

我正在尝试整理一个命令来从不同的表中提取数据并使用count()函数,但我无法正确使用它。

我需要获取服务的名称和描述以及count()在X年中完成服务的次数 我的桌子:

服务= id_service,描述,名称 history = id,id_service(它是服务的外键),年

任何帮助将不胜感激:D 我试过这样的东西,但它不起作用:S

select X.description, X.name, Z.year
from Services X
INNER JOIN history Z
ON Z.id_service = x.id_service AND Z.year= 2010;

1 个答案:

答案 0 :(得分:0)

关闭。您需要将COUNT()命令添加到您正在计数的字段中,并将其他字段添加到GROUP BY:

select X.description, X.name, Z.year, count(z.id_service)
from Services X
INNER JOIN history Z
ON Z.id_service = x.id_service -- AND Z.year= 2010 leave this off for a count from all years
GROUP BY X.description, X.name, Z.year