year 2020 not display when divideing two values from two table ?

ahmed salah 3,216 Reputation points
2022-02-21T10:15:32.797+00:00

i work on sql server 2014 i face issue year 2020 notr display when divide two values from two tables

so i divide all data for same company and year

so year 2020 not have row on table #tableconfirment

so if missing year i will suppose it will be 0

so how to handle that please

create table #tabletotal  
(  
companyid int,  
[year] int,  
cnt int  
)  
insert into #tabletotal(companyid,[year],cnt)  
select 1200,2015,20  
union  
select 1200,2016,25  
union  
select 1200,2017,30  
union  
select 1200,2018,15  
union  
select 1200,2019,12  
union  
select 1200,2020,10  
--drop table #tableconfirment  
create table #tableconfirment  
(  
companyid int,  
[year] int,  
cnt int  
)  
insert into #tableconfirment(companyid,[year],cnt)  
select 1200,2015,4  
union  
select 1200,2016,8  
union  
select 1200,2017,12  
union  
select 1200,2018,11  
union  
select 1200,2019,10  
  
  
select t.companyid,t.[year],t.cnt  
       / c.cnt as totalpercentage  from #tabletotal t  
inner join #tableconfirment c on t.companyid=c.companyid and t.[year]=c.[year]  

expected result

176327-image.png

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,672 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,624 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tom Phillips 17,731 Reputation points
    2022-02-21T14:48:09.587+00:00

    Just to be clear on Olaf's answer.

    You are using an INNER JOIN on #tableconfirment which does not contain a matching row for 2020. If you change INNER JOIN to OUTER JOIN, you will get all the rows from #tabletotal and NULL for 2020, which you then need to handle.


1 additional answer

Sort by: Most helpful
  1. Olaf Helper 44,301 Reputation points
    2022-02-21T13:43:44.043+00:00

    Use an OUTER JOIN (Left) with a CASE condition:

    select t.companyid,t.[year], 
           case when c.cnt IS NULL then 0 ELSE t.cnt / c.cnt END as totalpercentage  
    from #tabletotal t
         left join 
         #tableconfirment c on t.companyid=c.companyid and t.[year]=c.[year]
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.