我的数据库中有很多数据。我使用的是Mysql。
对于这种情况,我尝试使用一些查询显示第3周的数据:
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
我该如何解决这个问题? 感谢的
答案 0 :(得分:0)
我认为如果本月15日恰好是星期日(或星期一,具体取决于您的配置),您将在第一次查询时每Line
只获得一行。否则,根据WEEK
function,15日到21日将分两个星期。不过,我觉得你不需要按周分组。
虽然目前还不完全清楚你想做什么或者你的数据是什么样的,但我认为你应该按年份和可能的月份进行分组。
答案 1 :(得分:0)
只需从查询中删除它:
WHERE MONTH(Inspection_datetime) = MONTH(CURRENT_DATE)
AND YEAR(Inspection_datetime) = YEAR(CURRENT_DATE)
然后一切都能正常工作。