2016-10-04 50 views
-1

聯合收割機2計數SQL組我有2個表具有相同的結構,每個地方我使用幾乎相同的SQL來選擇和SUM。MYSQL:通過一年

SQL1:

SELECT YEAR, SUM(GENERATION) AS generationA, SUM(TRANSMISSION) AS transmissionA 
FROM tableA 
WHERE YEAR BETWEEN '2013' AND '2016' 
AND POWER_PLANT_ID = 'ABC1' 
AND STATUS = 'V' 
AND transmission IS NOT NULL 
GROUP BY YEAR 

SQL2:

SELECT YEAR, SUM(GENERATION) AS generationB, SUM(TRANSMISSION) AS transmissionB 
FROM tableB 
WHERE YEAR BETWEEN '2013' AND '2016' 
AND POWER_PLANT_ID = 'ABC1' 
AND STATUS = 'V' 
AND transmission IS NOT NULL 
GROUP BY YEAR 

如何通過其年這2 SQL來組結合?

+1

什麼是你期望的輸出?請提供一些樣本輸入和期望的輸出 – 1000111

回答

3

試試這個

select year, sum(generationA) as generationA, sum(transmissionA) as transmissionA from 
(
SELECT YEAR, SUM(GENERATION) AS generationA, SUM(TRANSMISSION) AS transmissionA 
FROM tableA 
WHERE YEAR BETWEEN '2013' AND '2016' 
AND POWER_PLANT_ID = 'ABC1' 
AND STATUS = 'V' 
AND transmission IS NOT NULL 
GROUP BY YEAR 
union all 
SELECT YEAR, SUM(GENERATION) AS generationB, SUM(TRANSMISSION) AS transmissionB 
FROM tableB 
WHERE YEAR BETWEEN '2013' AND '2016' 
AND POWER_PLANT_ID = 'ABC1' 
AND STATUS = 'V' 
AND transmission IS NOT NULL 
GROUP BY YEAR 
) as t 
group by YEAR 
+0

這項工作很好:)謝謝 – Teddybugs

1

您可以使用加入

SELECT 
      a.YEAR 
     , SUM(a.GENERATION) AS generationA 
     , SUM(a.TRANSMISSION) AS transmissionA 
     , SUM(b.GENERATION) AS generationB 
     , SUM(b.TRANSMISSION) AS transmissionB 
    FROM tableA as a 
    LEFT JOIN tableB as b on (a.YEAR = b.year 
           and a..POWER_PLANT_ID = b.POWER_PLANT_ID 
           and a.STATUS = b.STATUS 
           and a.transmission = b.transmission) 
    WHERE a.YEAR BETWEEN '2013' AND '2016' 
    AND a.POWER_PLANT_ID = 'ABC1' 
    AND a.STATUS = 'V' 
    AND a.transmission IS NOT NULL 
    GROUP BY a.YEAR 
1

嘗試用下面的腳本,如果你想用一年分組進行總結的結果集。

SELECT YEAR,SUM(GENERATION) generation,SUM(TRANSMISSION)TRANSMISSION 
FROM 
(SELECT YEAR, GENERATION , TRANSMISSION 
FROM tableA 
WHERE YEAR BETWEEN '2013' AND '2016' 
AND POWER_PLANT_ID = 'ABC1' 
AND STATUS = 'V' 
AND transmission IS NOT NULL 


UNION ALL 

SELECT YEAR, GENERATION, TRANSMISSION 
FROM tableB 
WHERE YEAR BETWEEN '2013' AND '2016' 
AND POWER_PLANT_ID = 'ABC1' 
AND STATUS = 'V' 
AND transmission IS NOT NULL)AS t 
GROUP BY YEAR