有一个表,如:
Year Month Value 2011 1 500 2011 2 550 2011 3 600 ... ... 2012 1 600 2012 2 750 2012 3 930
有没有一种方法可以计算相同月份/不同年份的值之间的差,因此得到的结果为:
Month Value 1 100 2 200 3 330 ...
我试图做类似的事情:
select month, a.value-b.value from (select month, value from table where year = 2012) a, (select month, value from table where year = 2011) b
但输出为选择a(2012)的12个月*选择b(2011)的12个月。
编辑:抱歉,缺少重要信息:
通过odbc:jdbc桥对Excel工作表进行查询。
因为“ from”子句始终是这样的:[sheet1 $]我无法创建任何联接或case :(
您的查询无效,因为您在表上执行CROSS JOIN(是因为,),因此每一行都与另一个表中的每一行都匹配,而不是INNER JOIN一个月匹配。
CROSS JOIN
,
INNER JOIN
修改查询:
select a.month, a.value-b.value from (select month, value from table where year = 2012) a JOIN (select month, value from table where year = 2011) b ON a.month = b.month
更快的查询:
select a.month, a.value-b.value from yourTable a join yourTable b on a.month = b.month where a.year = 2012 and b.year = 2011
每年每月多行:
select a.month, a.value-b.value from (select month, sum(value) as value from yourTable where year = 2012 group by month) a join (select month, sum(value) as value from yourTable where year = 2011 group by month) b on a.month = b.month
SQLFiddle。