SQL 如何将两个sql查询合并为一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7972015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to combine two sql queries into one
提问by Anthony
How can I combine these two SQL statements?
如何组合这两个 SQL 语句?
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.
hits10、hits11 和 hits12 存在于两个表中。
回答by Marc B
Use a UNION query - just stuff "UNION" between the two queries:
使用 UNION 查询 - 只是在两个查询之间填充“UNION”:
SELECT SUM(...) AS AEROWiz
FROM ...
UNION
SELECT SUM(...) AS AEROWiz
FROM ...
update
更新
wrap the union in yet another query:
将联合包装在另一个查询中:
SELECT SUM(AEROWiz)
FROM (
.... unioned queries here
) AS child
回答by Anthony
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 duplicates, and UNION
will not put duplicates in the query result. With the SUM()
aggregate, I'm guessing there's a good chance of duplication summations, so I'd go with UNION ALL
for this one.
使用UNION ALL
因为它允许重复,并且UNION
不会在查询结果中放置重复。有了SUM()
聚合,我猜重复求和的机会很大,所以我会选择UNION ALL
这个。
回答by Mark Byers
You could use two subselects:
您可以使用两个子选择:
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 may also want to consider normalizing your database so that you don't have a table for each year.
您可能还需要考虑规范化您的数据库,以便您没有每年的表。
回答by Arnaud F.
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'