我有一個需求,我需要o組數據到相同的ob行。由於MySQL沒有rownum()
我模仿這種行爲:MySQL左側加入子查詢組
SET @row:=6;
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count
FROM
(
SELECT timestamp, value, @row:[email protected]+1 AS row
FROM data
WHERE channel_id=52 AND timestamp >= 0 ORDER BY timestamp
) AS agg
GROUP BY row div 8
ORDER BY timestamp ASC;
注:根據Can grouped expressions be used with variable assignments?此查詢可能不是100%正確的,但它確實工作。
另一個要求是計算分組集合之間的行差異。我找了一個解決方案使用子查詢加入同一個表:
SET @row:=6;
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count
FROM
(
SELECT timestamp, value, @row:[email protected]+1 AS row
FROM data
WHERE channel_id=52 AND timestamp >= 0 ORDER BY timestamp
) AS agg
LEFT JOIN data AS prev
ON prev.channel_id = agg.channel_id
AND prev.timestamp = (
SELECT MAX(timestamp)
FROM data
WHERE data.channel_id = agg.channel_id
AND data.timestamp < MIN(agg.timestamp)
)
GROUP BY row div 8
ORDER BY timestamp ASC;
不幸的錯誤:
Error Code: 1054. Unknown column 'agg.channel_id' in 'on clause'
任何想法如何查詢可以寫?
它應該只是在'agg'子查詢的選擇列表中公開'channel_id'。當前你只有在'WHERE'子句中。 (我沒有分析是否會給你想要的結果,但它會清除1054錯誤) –