问题
I have a table sales_table
with a id,date and sales fields.
no date sales
----------------------------------------------------
1 1-Jan 10,000
2 3-Jan 12,500
3 4-Jan 8,000
4 5-Jan 12,000
5 8-Jan 10,000
" " "
" " "
" " "
" " "
" " "
" " "
" " "
" " "
" " "
100 13-Mar 4000
the date is unique but not always in series. the no is unique and in series with a incremented no of each higher date.
I am looking to get the difference between the sales of the current and previous date. something like
no date sales diff
------------------------------------------------------------------------------------------
1 1-Jan 10,000 0
2 3-Jan 12,500 2500
3 4-Jan 8,000 -4500
4 5-Jan 12,000 4000
5 8-Jan 10,000 -2000
I am using a sql query-
select t1.no,t1.date,t1.sales (t1.sales-2.sales) as diff
from sales_table as t1,sales_table as t2
where(t1.no=t2.no+1) order by t1.date
This works fine except i get records starting from no 2.
so i have written another another sql query -
select no,date,sales,sales-sales as diff
from sales_table
where(no=1)
which outputs as- 1, 1-Jan,10000,0.
How can i join rows from both these queries?
回答1:
There are a couple of different options depending on your database. One option is to modify your existing query to use an OUTER JOIN
:
select t1.no,t1.date,t1.sales,(t1.sales-coalesce(t2.sales,t1.sales)) as diff
from sales_table as t1
left join sales_table as t2 on t1.no=t2.no+1
order by t1.date
- SQL Fiddle Demo
来源:https://stackoverflow.com/questions/25945534/join-rows-from-two-different-queries