I have table MyNumbers with data for every number like below:
Number ServiceName ParameterName Value
10431 TypeA KeyCode1 14318
10431 TypeA KeyCode2 3213X
10431 TypeB KeyCode3 BlahBlah
For another Number:
Number ServiceName ParameterName Value
28659 TypeA KeyCode2 6712X
28659 TypeB KeyCode3 NewBlah
I need to Select for All Numbers at table and display their Value, even if the value is null or the row does not exist (like for Number 28659 above for which there is no row with ParameterName=KeyCode2. Note that for another dfferent than the above Number, the ServiceName=TypeB might be missing, etc...
The Select I am using is:
select mn1.Number, mn1.Value, mn2.Value, mn3.Value
from MyNumbers mn1, MyNumbers mn2, MyNumbers mn3
where mn2.Number = mn1.Number
and mn3.Number = mn1.Number
and mn1.ServiceName = 'TypeA'
and mn1.ParameterName = 'KeyCode1'
and mn2.ServiceName = 'TypeA'
and mn2.ParameterName = 'KeyCode2'
and mn3.ServiceName = 'TypeB'
and mn3.ParameterName = 'KeyCode3';
So, for Number=28659 this returns no rows at all, because there is no row with TypeA and KeyCode1. For such cases, I want to get the populated rows (for TypeA, KeyCode2 and TypeB, KeyCode3, at example above) and empty value for the non-existent row. So, output like:
10431, 3213X, 14318, BlahBlah
28659, , 6712X, NewBlah
The last line is never displayed, this is the problem, I want all existing data to display and for non-existent row to display empty string, like above.
Thank you.
With your approach, you can use LEFT JOIN
:
select mn1.Number, mn1.Value, mn2.Value, mn3.Value
from MyNumbers mn1 left join
MyNumbers mn2
on mn2.Number = mn1.Number and
mn2.ServiceName = 'TypeA' and
mn2.ParameterName = 'KeyCode2'left join
MyNumbers mn3
on mn3.Number = mn1.Number and
mn3.ServiceName = 'TypeB' and
mn3.ParameterName = 'KeyCode3'
where mn1.ServiceName = 'TypeA' and
mn1.ParameterName = 'KeyCode1';
Actually, this requires something in the first column. If you have a numbers table, then:
select mn1.Number, mn1.Value, mn2.Value, mn3.Value
from Numbers n left join
MyNumbers mn1
on n.Number = mn1.Number and
mn1.ServiceName = 'TypeA' and
mn1.ParameterName = 'KeyCode1' left join
MyNumbers mn2
on mn2.Number = n.Number and
mn2.ServiceName = 'TypeA' and
mn2.ParameterName = 'KeyCode2' left join
MyNumbers mn3
on mn3.Number = n.Number and
mn3.ServiceName = 'TypeB' and
mn3.ParameterName = 'KeyCode3';
You might want to add where mn1.Number is not null or mn2.Number is not null or mn3.Number is not null
if you want at least one column to have data.
Also, the Numbers
table could be replaced with (select distinct Number from MyNumbers)
.
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.