## Can a JOIN be used here instead of a UNION?

 Author Message david.dartnell Valued Member Group: General Forum Members Points: 62 Visits: 129 Hi Everyone,I am in the midst of writing a report which shows the 'Total Sales', 'Gross Profit', and 'Gross Profit %' by Sales Person. Traditionally I have used a UNION between two result sets to achieve this task. However I am wondering it if is possible to achieve the same outcome with a JOIN as shown below?`SELECT T0.SlpCode , T0.SalesPerson , T0.Branch , (T0.TotalSales - T1.TotalSales) AS 'Total Sales' , ((T0.TotalSales - T1.TotalSales) - (T0.StockValue + T1.StockValue)) AS 'Gross Profit' , CAST(((T0.TotalSales - T1.TotalSales) - (T0.StockValue + T1.StockValue)) / NULLIF((T0.StockValue + T1.StockValue), 0) * 100 AS decimal(15,2)) AS 'Gross Profit %' FROM ( /*** SAP - Invoices by Sales Person ***/ SELECT T1.SlpCode , T2.SlpName AS 'SalesPerson' , T2.U_INE_Branch AS 'Branch' , CAST(SUM(T0.LineTotal) AS decimal(15,2)) AS 'TotalSales' , CAST(SUM(T0.StockValue) AS decimal(15,2)) AS 'StockValue' FROM AU.dbo.INV1 T0 INNER JOIN AU.dbo.OINV T1 ON T1.DocEntry = T0.DocEntry LEFT JOIN AU.dbo.OSLP T2 ON T2.SlpCode = T1.SlpCode WHERE T1.DocDate >= '2014-08-01' AND T1.DocDate <= '2014-09-01' GROUP BY T1.SlpCode, T2.SlpName, T2.U_INE_Branch ) AS T0 FULL JOIN ( /*** SAP - Credits by Sales Person ***/ SELECT T1.SlpCode , T2.SlpName AS 'SalesPerson' , T2.U_INE_Branch AS 'Branch' , ISNULL(CAST(SUM(T0.LineTotal) AS decimal(15,2)), 0) AS 'TotalSales' , ISNULL(CAST(SUM(T0.StockValue) AS decimal(15,2)), 0) AS 'StockValue' FROM AU.dbo.RIN1 T0 INNER JOIN AU.dbo.ORIN T1 ON T1.DocEntry = T0.DocEntry LEFT JOIN AU.dbo.OSLP T2 ON T2.SlpCode = T1.SlpCode WHERE T1.DocDate >= '2014-08-01' AND T1.DocDate <= '2014-09-01' GROUP BY T1.SlpCode, T2.SlpName, T2.U_INE_Branch ) AS T1ON T1.SalesPerson = T0.SalesPerson`Currently I am not getting correct results (which I can do through a UNION), but am instead seeing NULLs scattered throughout, as shown below...(I have blacked out certain details to keep the company I work for anonymous)My question is: are NULLs unavoidable in this scenario simply because of the nature of JOINs? I have tried a 'JOIN' rather than a 'FULL JOIN' but instead of seeing all of the Sales People I only see Sales People who do not have NULLs, which looks nice but is not particularly accurate.Any help and suggestions here will be greatly appreciated.Kind Regards,David ChrisM@Work SSCrazy Eights Group: General Forum Members Points: 8975 Visits: 19028 david.dartnell (9/3/2014)Hi Everyone,I am in the midst of writing a report which shows the 'Total Sales', 'Gross Profit', and 'Gross Profit %' by Sales Person. Traditionally I have used a UNION between two result sets to achieve this task. However I am wondering it if is possible to achieve the same outcome with a JOIN as shown below?...Hi DavidIt looks like your suggestion will work for you, however you will have to account for null values from both tables. Try changing the outer query to thisSELECT T0.*, '#' '#', T1.*to see what I mean. A full outer join will return matching rows between the two tables, and rows from both tables where there's no match in the other. Where there's no match, the output columns will be null.Also, I think you should either include branch in your join, or exclude it from the GROUP BY. “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail ShawFor fast, accurate and documented assistance in answering your questions, please read this article.Understanding and using APPLY, (I) and (II) Paul White Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff ModenExploring Recursive CTEs by Example Dwain Camps david.dartnell Valued Member Group: General Forum Members Points: 62 Visits: 129 Hi ChrisM@Work,Thank you for your suggestions. I have now managed to find the line in my query which is returning NULL values.`(T0.TotalSales - T0.StockValue) / NULLIF(T0.StockValue, 0) AS 'Gross Profit %'`I have identified that the NULLIF(T0.StockValue, 0) section of the above line is responsible, even more specifically the T0.StockValue column itself seems to be the source of my challenge. If I modify the above line by replacing T0.StockValue with 0 then I get nothing but NULLs in my result set.e.g.: NULLIF(0, 0) gives nothing but NULLsOn the other hand if I substitute the number 1 in place of T0.StockValue I get NO NULLs.e.g.: NULLIF(1, 0) gives a complete set of values, with NO NULLs.I have used a similar line of SQL in another query and it did not return any NULLs, the line is as follows -`(sum(T0.LineTotal - T0.StockValue) / nullif(sum(T0.StockValue), 0)) * 100 as 'Profit %'`Above I am summing a collection of values so I suppose there is less likely to be a NULL?At any rate if you have any more suggestions please let me know.Kind Regards,David ChrisM@Work SSCrazy Eights Group: General Forum Members Points: 8975 Visits: 19028 david.dartnell (9/3/2014)Hi ChrisM@Work,Thank you for your suggestions. I have now managed to find the line in my query which is returning NULL values.`(T0.TotalSales - T0.StockValue) / NULLIF(T0.StockValue, 0) AS 'Gross Profit %'`I have identified that the NULLIF(T0.StockValue, 0) section of the above line is responsible, even more specifically the T0.StockValue column itself seems to be the source of my challenge. If I modify the above line by replacing T0.StockValue with 0 then I get nothing but NULLs in my result set.e.g.: NULLIF(0, 0) gives nothing but NULLsOn the other hand if I substitute the number 1 in place of T0.StockValue I get NO NULLs.e.g.: NULLIF(1, 0) gives a complete set of values, with NO NULLs.I have used a similar line of SQL in another query and it did not return any NULLs, the line is as follows -`(sum(T0.LineTotal - T0.StockValue) / nullif(sum(T0.StockValue), 0)) * 100 as 'Profit %'`Above I am summing a collection of values so I suppose there is less likely to be a NULL?At any rate if you have any more suggestions please let me know.Kind Regards,DavidHi DavidYou've gone off on a bit of a tangent here so we'll deal with this first.Function NULLIF() takes two parameters, p1 and p2. If they are different then p1 is returned, otherwise NULL is returned with data type same as p1.Removing NULLIF from your expression above yields this:sum(T0.LineTotal - T0.StockValue) / sum(T0.StockValue) - which will raise a "divide by zero" error if sum(T0.StockValue) evaluates to 0. Replacing that 0 with NULL quietly yields NULL as the result of the expression. That's what the NULLIF is for - letting the expression complete without raising an error, when sum(T0.StockValue) evaluates to 0. If you don't like NULL appearing in the result, then change it to 0 using ISNULL(), wrapped around the whole expression like this:ISNULL((sum(T0.LineTotal - T0.StockValue) / NULLIF(sum(T0.StockValue), 0)) * 100,0)No NULL, no error, no incorrect result. “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail ShawFor fast, accurate and documented assistance in answering your questions, please read this article.Understanding and using APPLY, (I) and (II) Paul White Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff ModenExploring Recursive CTEs by Example Dwain Camps david.dartnell Valued Member Group: General Forum Members Points: 62 Visits: 129 Thanks Chris, your explanation is very helpful. I now have a much better understanding of NULLIF and ISNULL.

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 14 - Administration      SQL Server 14 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      SQL Server Security Skills      Question of the Day (QOD) Microsoft Access      Microsoft Access Products and Books      Third Party Products         SQLCentric         Extreme Technologies.         Embarcadero         SQL Sentry         Sonasoft         Golden Gate Software         Idera         Lumigent         Red Gate Software         Innovartis         Quest Software         ApexSQL         CA      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12