我正在学习MySQL,并在网站上练习练习题(未命名,但它是问题81)。问题在于GROUP BY之后的字段序列。我确定GROUP BY之后的字段序列会影响查询结果,这些结果基于报告中隐藏表的预期行数和实际行数之间的比较结果。我对这个网站和其他人的大量阅读理解是没有关系的。GROUP BY字段的序列影响MySQL查询结果
的任务是:
From Outcome table, retrieve all rows for that month (months)
in view of a year, in which total value of expenses (out) is maximal.
表描述是:
Outcome(code, point, date, out) where code is the primary key,
point is a simple integer, date is in the format datetime, and out is a currency value.
这里是我的查询:
SELECT code,point,date,`out` outc FROM outcome
WHERE EXTRACT(MONTH FROM date) =
(SELECT mon bestmonth FROM
(SELECT MAX(sout), mon,yr FROM
(SELECT SUM(outc) sout,mon,yr FROM
(SELECT EXTRACT(MONTH FROM date) mon, `out` outc,
date,EXTRACT(YEAR FROM date) yr FROM outcome
) maxmonth GROUP BY mon,yr
) peak
) tmonth
)
AND EXTRACT(YEAR FROM date) =
(SELECT yr bestyear FROM
(SELECT MAX(yout), mon,yr FROM
(SELECT SUM(outy) yout,mon,yr FROM
(SELECT EXTRACT(MONTH FROM date) mon, `out` outy,
date,EXTRACT(YEAR FROM date) yr FROM outcome
) maxyear GROUP BY yr,mon
) peakb
) tyear
)
虽然不是一个优雅的查询,我想明白为什么在maxmonth和maxyear子查询中将顺序从“GROUP BY mon,yr”更改为“GROUP BY yr,mon”会有任何影响。
在maxmonth子查询, 'GROUP BY星期一,年' 的结果:
Wrong Your query produced correct result set on main database,
but it failed test on second, checking database
* Wrong number of records (less by 6)
出于同样的maxmonth子查询, 'GROUP BY年,星期一' 的结果:
Wrong Your query produced correct result set on main database,
but it failed test on second, checking database
* Wrong number of records (less by 11)
这是一个疯狂的查询。这是对原始问题81的翻译吗? – Strawberry