我有2个具有相同结构的表,每个表使用几乎相同的sql来选择和SUM。
SQL1:
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
SQL2:
AssertionError
如何将这个2 sql组合到其年份?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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