Join rows from two different queries

痴心易碎 提交于 2020-01-07 03:12:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!