[英]SQL Query that counts grouped by results not working as intended
我的目标是要获得一张可以计算游戏正确答案的表格。
例如我想要这个
| G.Name | E.Action | game 1 | correctAnswer | game 1 | correctAnswer | game 2 | correctAnswer | game 3 | correctAnswer | game 3 | correctAnswer
成为这个
| G.Name | Count(*) | game 1 | 2 | game 2 | 1 | game 3 | 2
问题是我得到这个代替:
| G.Name | Count(*) | game 1 | 5 | game 2 | 5 | game 3 | 5
其中5是2 + 1 + 2的总和
这是我的查询
SELECT G.Name, Count(*) FROM enduser EU INNER JOIN prescription P ON EU.UserRefID = P.EndUserRefID INNER JOIN prescriptiongame PG ON PG.PrescriptionRefID = P.PrescriptionID INNER JOIN games G ON G.GameID = PG.GameRefID INNER JOIN session S ON S.PrescriptionRefID = P.PrescriptionID INNER JOIN entries E ON E.SessionGameRefID = S.Session WHERE P.EndUserRefID = 889 AND E.Action = 'correctAnswer' GROUP BY G.Name ORDER BY G.Name
当我用谷歌搜索人们使用相同方法但获得良好结果时,如何解决此问题
提前致谢
我敢打赌,您的加入之一正在夸大结果。 将查询简化为关键表: prescription
, session
和entries
。 您仍然得到过多的结果吗? 如果不是,请尝试一次重新加入联接,直到您过度计数为止。
您的联接以某种方式使行数成倍增加。 当您沿彼此不相关的不同维度联接表时,会发生这种情况。 这是一个普遍的问题,但是我不了解您的数据结构,因此以下是最好的猜测。
您的示例可以通过在某物上使用count(distinct)
解决。 所以试试这个:
SELECT G.Name, Count(distinct SessionGameRefID)
session
和game
之间应该有关系吗?
我想知道您对查询的这种简化是否可以解决问题(它删除了前两个表):
SELECT G.Name, Count(*)
FROM prescriptiongame PG
INNER JOIN games G
ON G.GameID = PG.GameRefID
INNER JOIN session S
ON S.PrescriptionRefID = PG.PrescriptionRefID
INNER JOIN entries E
ON E.SessionGameRefID = S.Session
WHERE PG.EndUserRefID = 889
AND E.Action = 'correctAnswer'
GROUP BY G.Name
ORDER BY G.Name;
假设需要所有联接,请尝试以下查询:
SELECT G.Name, Count(G.Name)
FROM enduser EU
INNER JOIN prescription P
ON EU.UserRefID = P.EndUserRefID
INNER JOIN prescriptiongame PG
ON PG.PrescriptionRefID = P.PrescriptionID
INNER JOIN games G
ON G.GameID = PG.GameRefID
INNER JOIN session S
ON S.PrescriptionRefID = P.PrescriptionID
INNER JOIN entries E
ON E.SessionGameRefID = S.Session
WHERE P.EndUserRefID = 889
AND E.Action = 'correctAnswer'
GROUP BY G.Name
ORDER BY G.Name
select G.Name , count(*) from enduser EU, prescription P,prescriptiongame PG ,
games G ,session S ,entries E where P.EndUserRefID = 889 and E.action='correctAnswer' and (EU.UserRefID = P.EndUserRefID) and (PG.PrescriptionRefID = P.PrescriptionID) and (G.GameID = PG.GameRefID) and (S.PrescriptionRefID = P.PrescriptionID) and (E.SessionGameRefID = S.Session)
GROUP BY G.Name
ORDER BY G.Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.