我正在尝试运行此查询,但它仍然失败。任何人都知道可能出现的问题?
SELECT *, DATEDIFF(`date1`,`date2`) AS `date_difference_value`,
AVG(`difference`) FROM (
SELECT DATEDIFF(`date1`,`date2`) AS `difference`
FROM `datetable`
WHERE MONTH(`date2`) = '08'
AND `date1` <> '0000-00-00'
AND `date2` <> '0000-00-00'
) AS `average`
FROM `datetable`
WHERE MONTH(`date2`) = '08'
答案 0 :(得分:0)
看起来您想要计算月平均值,然后在每行输出该值以及date1和date2详细信息。
对我来说,现有查询中最明显的错误是你有2个FROM子句
SELECT * , DATEDIFF(`date1`, `date2`) AS `date_difference_value` , AVG(`difference`) FROM ( SELECT DATEDIFF(`date1`, `date2`) AS `difference` FROM `datetable` WHERE MONTH(`date2`) = '08' AND `date1` != '0000-00-00' AND `date2` < '0000-00-00' ) AS `average` FROM `datetable` WHERE MONTH(`date2`) = '08'
如果我对您的要求的猜测是正确的,那么以下内容可能适用:
SELECT
`datetable`.*
, DATEDIFF(`date1`, `date2`) AS `date_difference_value`
, `average`.`avg_difference`
FROM `datetable`
CROSS JOIN (
SELECT AVG(DATEDIFF(`date1`, `date2`)) AS `avg_difference`
FROM `datetable`
WHERE MONTH(`date2`) = 8
) AS `average`
WHERE MONTH(`date2`) = 8
注意:
date2
)=&#39; 08&#39;不会是真的date1
&lt;&gt; &#39; 0000-00-00&#39;&#34; (你可能需要它,我不能确定你是否这样做)。也许您需要 AND date1
IS NOT NULL