使用 Left Join 显示第三周数据错误结果
我的数据库中有很多数据。我正在使用Mysql。
对于这种情况,我尝试使用一些查询来显示第三周的数据:
SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1)/COUNT(Serial_number) AS 3rd
FROM inspection_report
WHERE DAY(Inspection_datetime) BETWEEN 15 AND 21
GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)
但结果显示为:
line count
fa 01 0.0000
fa 01 0.0000
fa 02 0.0000
fa 02 0.0000
fa 03 0.0000
fa 03 0.0260
它使数据显示两次。然后我尝试这个查询:
SELECT id,A.Line,week3.3rd
FROM inspection_report AS A
LEFT JOIN(
SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1)/COUNT(Serial_number) AS 3rd
FROM inspection_report
WHERE DAY(Inspection_datetime) BETWEEN 15 AND 21
GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)
) AS week3 USING (Line)
WHERE MONTH(Inspection_datetime) = MONTH(CURRENT_DATE)
AND YEAR(Inspection_datetime) = YEAR(CURRENT_DATE)
GROUP BY Line
但结果显示为:
line count
fa 01 0.0000
fa 02 0.0000
fa 03 0.0000 //must be 0.0260
我该如何解决这个问题? 谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为,如果该月的 15 日恰好是星期日(或星期一,具体取决于您的配置),则在第一个查询中,您只会获得每行一行。否则,根据
WEEK
函数。不过,我认为您不需要按周分组。尽管尚不完全清楚您想要做什么或您的数据是什么样子,但我认为您应该可以按年甚至月进行分组。
I think you'll only get one row per
Line
on the first query if the 15th of the month happens to be a Sunday (or Monday depending on your configuration). Otherwise, the 15th through the 21st will be on two different weeks according to theWEEK
function. I don't think you need to group by the week, however.Although it's not entirely clear what you want to do or what your data looks like, I think you should be ok grouping by year and possibly month.
只需将其从查询中删除即可:
然后一切都可以正常工作。
Just remove this from query:
and then all can work normally.