Subquery
計算最大和連接表
只需要一點幫助,就像 SQL 的新手一樣。
我有一個表格,其中包含閱讀時間(白天每 4 秒記錄一次)和能量讀數。我想知道一天消耗了多少能量。這是我使用的查詢
SELECT date(readingtime), max(energy)-min(energy)as total FROM lights_1 WHERE readingtime between 20140407000000 and 20140409235959 GROUP BY date(readingtime) LIMIT 0,30;
這給了我 1 張桌子所需的結果。我有 4 個這些lights_2、Lights_3、lights_4 的表格,我想將它們一起顯示,從而匹配閱讀時間,因此每天都有所有表格的能量需求和總數。當我嘗試加入表格時,我得到了很多錯誤!
任何人都可以幫忙。
謝謝
聯盟給
date(readingtime) total 2014-04-07 1244 2014-04-08 1039 2014-04-09 1389 2014-04-07 419 2014-04-08 1102 2014-04-09 482
我想
date(readingtime) total_1 total_2 2014-04-07 1244 419 2014-04-08 1039 1039 2014-04-09 1389 1389
SELECT date(lights_1.readingtime), max(lights_1.energy)-min(lights_1.energy)as total_1, max(lights_2.energy)-min(lights_2.energy)as total_2 FROM lights_1 join lights_2 on lights_1.readingtime = lights_2.readingtime WHERE lights_1.readingtime between 20140407000000 and 20140409235959 GROUP BY date(lights_1.readingtime) LIMIT 0,30
您首先需要
UNION
表格:SELECT date(readingtime), max(energy)-min(energy)as total FROM lights_1 WHERE readingtime between 20140407000000 and 20140409235959 GROUP BY date(readingtime) LIMIT 0,30 UNION SELECT date(readingtime), max(energy)-min(energy)as total FROM lights_2 WHERE readingtime between 20140407000000 and 20140409235959 GROUP BY date(readingtime) LIMIT 0,30 UNION SELECT date(readingtime), max(energy)-min(energy)as total FROM lights_3 WHERE readingtime between 20140407000000 and 20140409235959 GROUP BY date(readingtime) LIMIT 0,30 SELECT date(readingtime), max(energy)-min(energy)as total FROM lights_4 WHERE readingtime between 20140407000000 and 20140409235959 GROUP BY date(readingtime) LIMIT 0,30;
然後,您將需要旋轉此查詢的結果。我假設您使用的是 MySQL?我可以為你找出一切,但如果你去學習如何旋轉數據以按照你想要的方式獲得它可能會更好,以下是一個很好的總結! http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/