简体   繁体   中英

Left join same table with nulls

I'm currently developing my first C# program. In the back-end I'm using MS SQL as database where I have to create a report to show in my program.

I have one big table with data from the ERP-system. In this table are all the articles which are sold every month.

Now I have created a query to compare the same month from different years.

select  A1.ArticleID, A2.ArticleID
from Revenue A1
left join Revenue A2
on A1.Articlenr = A2.ArticleID
where A1.articleyear = 2017 and A2.articleyear=A1.articleyear-1 and A1.articlemonth = 1 and A2.articlemonth=A1.articlemonth
order by A1.ArticleID

With this query I only receive the articles which are sold in both years. But I don't receive the articles which are sold in 2017 but not in 2016.

How can I force the query to see those articles as well?

All the conditions on the second table need to be in the ON clause for LEFT JOIN :

select A1.ArticleID, A2.ArticleID
from Revenue A1 left join
     Revenue A2
     on A1.Articlenr = A2.ArticleID and
        A2.articlemonth = A1.articlemonth and
         A2.articleyear = A1.articleyear-1
where A1.articleyear = 2017 and A1.articlemonth = 1 and 
order by A1.ArticleID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM