数据年明智的sql

时间:2017-01-03 06:23:38

标签: sql-server count

我试图获得年度数据。我试过这个查询

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

1 个答案:

答案 0 :(得分:2)

请尝试以下查询..垫帮助

      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