Sql连接表

时间:2014-01-26 15:30:46

标签: sql sql-server

我有两个表作为A,B。表A保存我的类别名称,表B保存 我的fk_tbl_A,时间,机器名称。

我想计算一下我用于每台机器的时间,并按fk_abl_A分组 我在SQL 2012中编写了以下代码:

select sum(cast(a.during_time as int))
from dbo.sabt_bazdid as a join
     dbo.ability as b
     on a.fk_operator_ability = b.id
Group by a.fk_operator_ability 

这里的代码运行良好,但是当我想在表A中显示类别的名称时, Sql显示错误。

select b.name, sum(cast(a.during_time as int))
from dbo.sabt_bazdid as a join
     dbo.ability as b
     on a.fk_operator_ability = b.id
Group by a.fk_operator_ability 

请帮我解决问题 感谢。

2 个答案:

答案 0 :(得分:0)

b.name不在group by子句中。您需要将其放在那里或将其放在聚合函数中:

select b.name, sum(cast(a.during_time as int))
from dbo.sabt_bazdid as a join
     dbo.ability as b
     on a.fk_operator_ability = b.id
Group by b.name, a.fk_operator_ability;

答案 1 :(得分:0)

您需要将b.name放在group by子句中或聚合函数中。只需将b.name属性放在group by子句中。

select b.name,sum(cast(a.during_time as int))
from dbo.sabt_bazdid as a join
     dbo.ability as b
     on a.fk_operator_ability = b.id
Group by a.fk_operator_ability ,b.name

这是运行查询。