2013-06-25 49 views
0
table1        table2 
id name logo       id name value 
1 a asd       1 a  2 
2 b asd       2 a  3 
3 c asd       3 b  4 

查詢:內連接是給一個結果時,應該給予更多的

SELECT table1.id,table1.logo,avg(table2.value) as average, 
    count(table2.id) as no FROM table1 INNER JOIN table2 ON table1.name = table2.name 
    ORDER BY no 

這段代碼給出比2分的結果

+1

不好用的骨料沒有適當GROUP BY - *包括在所有非聚合列通過...分組*。解決這個問題,問題應該「自行修復」。 (SQL Server會簡單地並且正確地拒絕這個計劃。) – user2246674

回答

1

結果只有一個,因爲你沒有GROUP BY條款,嘗試添加一個。

SELECT a.name, 
     a.logo, 
     AVG(b.value) avg_val, 
     COUNT(*) no 
FROM table1 a 
     INNER JOIN table2 b 
      ON a.name = b.name 
GROUP BY a.Name 
ORDER BY no 
0

FROM REFERENCE

如果你在不包含 GROUP BY子句的語句中使用的一組功能,它相當於對所有行分組。

所以使用組通過

SELECT table1.id,table1.logo,avg(table2.value) as average, 
     count(table2.id) as no 

FROM table1 INNER JOIN table2 
ON table1.name = table2.name 

GROUP BY table1.name 
ORDER BY no 

,你應該罰款

查閱SQL FIDDLE