2017-01-03 65 views
1

我試圖獲得明智的數據。我想這個查詢數據年明智sql

select 
    year(SStartDate) as joinedyear , 
    count(*) joined_total 
from 
    Detail 
where 
    client = 81 
Group By 
    YEAR(StartDate) 

union all 

select 
    year(SEndDate) as leftyear, 
    count(*) left_total 
from 
    Detail 
where 
    client = 81 
Group By 
    YEAR(SEndDate) 

這顯示正確的數據,但該這樣表示

1900 12 
2001 1 
2012 3 
2013 3 
2016 45 
1900 23 
2002 34 
2004 34 
2015 1 
2016 56 

數據,其中,因爲我想這樣

joinedyear joined_total leftyear left_total 

1900   12   1900  45 
2001   1   2002  34  
2012   3   2004  34 
2013   3   2015  1  
2016   45   2016  56 
+0

是使用聯合a二。嘗試使用內部連接使用連接表。 –

回答

2

數據可以嘗試下面query..it墊這幫助你

 select * from (
    select year(SStartDate) as joinedyear , 
    count(*) joined_total from Detail 
    where client=81 
    Group By YEAR(StartDate) 
    ) as a 
    full outer join 
    (
    select year(SEndDate) as leftyear , count(*) left_total from Detail 
    where client=81 
    Group By YEAR(SEndDate) 
    ) as b 
    on a.joinedyear=b.leftyear