2013-09-27 119 views
0

計數(B組)我想運行SQL Server的查詢,以便從另一個表SQL服務器選擇A. *,通過

select a.*, count(b.number) from tableA a 
inner join tableB b on a.id = b.a_id 
group by a.id; 

此選中所有的表(表A)與集料的元素給出以下錯誤:

Error: Column 'a.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

SQLState: S1000
ErrorCode: 8120

什麼是正確的查詢來得到我想要的?

回答

1

您可以使用

select a.*, x.number 
from tableA a 
inner join 
    (select b.a_id, count(b.number) number 
    from tableB b 
    group by b.a_id) x 
on x.a_id = a.id 
0
select a.*, 
     (Select count(b.number) from tableB b where b.a_id = a.id) as "b count" 
    from tableA a; 
0

在通過有組查詢,所有列應與聚合函數出現或列表組提了。 您的錯誤是因爲您的表格'a'列除id以外,沒有按列表分組,並且沒有出現集合函數。

0
select a.*, B.number 
from tableA a 
inner join 
(
a.id a_id, count(b.number) number from tableA a 
inner join tableB b on a.id = b.a_id 
group by a.id; 
) B on B.a_id = a.id 
0

由於使用a.*你是從tableA選擇所有列。當使用aggrgate功能grouby或其他任何你必須在group by子句中提及列名稱。試試這種方式

select a.id,a.name, count(b.number) from tableA a 
inner join tableB b on a.id = b.a_id 
group by a.id,a.name 

如果你想從tableA中選擇所有列,那麼你不能使用group by。

select a.*, count(b.number) from tableA a 
inner join tableB b on a.id = b.a_id