2017-04-09 97 views
0

我有一個數據庫與下面提到的關係表。我希望獲得每個客戶給出的每種產品的平均分數,如所需的輸出所示。SQLite - 查詢返回相關記錄

「GRP」

g_id g_name 
1  Ag.f 
2  Gh.h 

「客戶」,其中c_g_id引用在 「GRP」

c_id c_name g_id 
"1"  "DA"  "1" 
"2"  "AŠ"  "1" 
"3"  "EK"  "1" 
"4"  "PK"  "1" 
"5"  "DD"  "2" 
"6"  "AA"  "2" 
"7"  "EE"  "2" 

「產品」,其中G_ID引用在 「GRP」 G_ID

m_id sequence_no g_id name 

"1"  "1"   "1" "product1" 
"2"  "2"   "1" "product2" 
"3"  "3"   "1" "product3" 
"4"  "1"   "2" "p1" 
"5"  "2"   "2" "p2" 
G_ID

「scores」

個C_ID引用在C_ID產品 「「客戶 M_ID引用到M_ID」

score_id customer_name c_id m_id score 

"1"   "DA"   "1"  "1"  "2" 
"2"   "DA"   "1"  "2"  "2" 
"3"   "DA"   "1"  "3"  "2" 
"4"   "AŠ"   "2"  "1"  "3" 
"5"   "AŠ"   "2"  "2"  "2" 
"6"   "AŠ"   "2"  "3"  "3" 
"7"   "EK"   "3"  "1"  "2" 
"8"   "EK"   "3"  "2"  "3" 
"9"   "EK"   "3"  "3"  "1" 
"10"  "PK"   "4"  "1"  "2" 
"11"  "PK"   "4"  "2"  "3" 
"12"  "PK"   "4"  "3"  "1" 
"13"  "DD"   "5"  "4"  "2" 
"14"  "DD"   "5"  "5"  "2" 
"15"  "AA"   "6"  "4"  "3" 
"16"  "AA"   "6"  "5"  "2" 
"17"  "EE"   "7"  "4"  "2" 
"18"  "EE"   "7"  "5"  "3" 

所需的輸出:

sequence_no g_id name  avg.score 
1   1  "product1" (2+3+2+2)/4 
2   1  "product2" (2+2+3+3)/4 
3   1  "product3" (2+3+1+1)/4 
+0

那麼你有三ED? – paddy

回答

1

您coudl通過

select products.name, products.g_id, avg(score) 
from scores 
inner join products on products.m_id = scores.m_id 
group by products.name, products.g_id 

最終使用AVG函數和組你可以加入其他的表,如果你需要一些相關的列

+0

聯合聲明將如何顯示,請問您能告訴我嗎? – DynamicQ

+0

答案已更新。 – scaisEdge