Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Implied Null values in joined table

In joining two tables with a one to many relationship, I want a result displaying all the values in the many table with null values in the one table.

Here's an example:

tbl_Platform: PriKey = PlatformID

PlatformID  PlatformDesc
1   Application
2   Cloud
3   Storage
4   Backup

tbl_Missed: PriKey= CustomerID+Week+PlatformID

CustomerID  Week    Missed     Platform ID
49          1       2017-05-19  1

Output desired:

CustomerID  Week    Missed  PlatformDesc
49  1   2017-05-19  Application
49  1   null    Cloud
49  1   null    Storage
49  1   null    Backup

The closest I've been able to come is using a cross join as follows:

SELECT        
   dbo.tbl_Missed.CustomerID, 
   dbo.tbl_Missed.Week, 
   dbo.tbl_Missed.Missed, 
   dbo.tbl_Platform.PlatformDesc
FROM
   dbo.tbl_Platform 
CROSS JOIN dbo.tbl_MissedSPT 

Which gives me:

49  1   2017-05-19  Application
49  1   2017-05-19  Cloud
49  1   2017-05-19  Storage
49  1   2017-05-19  Backup
like image 509
Smitty Avatar asked Apr 15 '26 23:04

Smitty


1 Answers

It seems as if you want to take the value of attribute missed if there is a match in platformID, and null otherwise. Try the following (hope there are no typos):

SELECT        
   dbo.tbl_Missed.CustomerID, 
   dbo.tbl_Missed.week, 
   CASE WHEN dbo.tbl_Missed.PlatformID = dbo.tbl_Platform.PlatformID
               THEN dbo.tbl_Missed.missed 
               ELSE NULL
   END as missed, 
   dbo.tbl_Platform.PlatformDesc
FROM dbo.tbl_Platform CROSS JOIN dbo.tbl_MissedSPT
like image 115
Stephan Lechner Avatar answered Apr 18 '26 17:04

Stephan Lechner