Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

sql - How to calculate between different group of rows of the same table

Having a table as:

Year   Month   Value
2011   1       500
2011   2       550
2011   3       600
...
...
2012   1       600
2012   2       750
2012   3       930

Is there a way I can calculate the difference between values of same month/different years, so to get a result as:

Month    Value
1        100
2        200
3        330
...

I tried to do something like:

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

but the output is 12 months (of select a (2012) * 12 month of select b (2011)..


edit: sorry for the lack of important information:

The queries are being made to a excel sheet via odbc:jdbc bridge.

as the "from" clause is always like this: [sheet1$] i'm not being able to create any joins or case :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You were very close to how to get the result. I would suggest using something similar to this which pivots the data into columns and then you can take the difference between each year:

select month,
  Year2012-Year2011 as Diff
from
(
  select month,
    sum(case when year = 2011 then value end) Year2011,
    sum(case when year = 2012 then value end) Year2012
  from yourtable
  group by month
) src     

See SQL Fiddle with Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...