How to combine two sql queries into one

How can I combine these two SQL statements?

SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09) AS 'AEROwiz' FROM tbl_2011 WHERE appName='AEROwiz' SELECT SUM(hits10 + hits11 + hits12) AS 'AEROwiz' FROM tbl_2010 WHERE appName='AEROwiz' 

hits10, hits11 and hits12 exist in both tables.

+6
source share
4 answers

Use the UNION query - just enter β€œUNION” between the two queries:

 SELECT SUM(...) AS AEROWiz FROM ... UNION SELECT SUM(...) AS AEROWiz FROM ... 

Update

combine union into another query:

 SELECT SUM(AEROWiz) FROM ( .... unioned queries here ) AS child 
+7
source
 SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09) AS 'AEROwiz' FROM tbl_2011 WHERE appName='AEROwiz' UNION ALL SELECT SUM(hits10 + hits11 + hits12) AS 'AEROwiz' FROM tbl_2010 WHERE appName='AEROwiz' 

Use UNION ALL as it will allow duplication, and UNION will not put duplicates in the query result. With the SUM() aggregate, I assume there are good chances of duplication, so I would go with UNION ALL for that.

+4
source

You can use two subqueries:

 SELECT ( SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09) FROM tbl_2011 WHERE appName='AEROwiz' ) T1 + ( SELECT SUM(hits10 + hits11 + hits12) FROM tbl_2010 WHERE appName='AEROwiz' ) T2 AS AEROwiz 

You can also consider normalizing your database so that you do not have a table for each year.

+2
source
 SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09 + t2010.hits10 + t2010.hits11 + t2010.hits12) AS 'AEROwiz' FROM tbl_2010 t2010 JOIN tbl_2011 t2011 ON t2010.appName = t2011.appName WHERE t2010.appName='AEROwiz' 
0
source

Source: https://habr.com/ru/post/900555/


All Articles