I have a view I want to select those records whose (Letter
, pro
, record
, and education
) column values are not null
.
For details, I want to check record MI13900454 that his (Letter
, pro
, record
, and education
) should not be null. Note: if we select ... from xxx where record_id is not null and letter_id is not null .....
it is not correct because values are not in same row – they are in different rows and columns.
Plaintext table:
| ID | LETTER_ID | MEDICAL_ID | SICKNESS_ID | PRO_ID | EDU_ID | TRAINING_ID | RECORD_ID | NID |
|-----------|-----------|------------|-------------|---------|--------|-------------|-----------|--------|
| MI1390454 | | | | | | 47584 | | |
| MI1390454 | | | | 4673735 | | | | |
| MI1390033 | | | | 105419 | | | | |
| MI1390033 | | | | | | | | |
| MI1390033 | | | | | | | | |
| MI1390033 | 299080 | | | | | | | |
| MI1390033 | | | | | 659652 | | | |
| MI1390033 | | 309609 | | | | | | |
| MI1390033 | | | | | | | | |
| MI1390033 | | | | | | | | |
| MI1390033 | | | | | 659650 | | | |
| MI1390033 | | | | | 659654 | | | |
| MI1390033 | | | | | | | | 161077 |
| MI1390033 | | 309608 | | | | | | |
| MI1390033 | | | | | 659651 | | | |
| MI1390454 | | | | | | | 154745 | |
| MI1390033 | | | | | 659653 | | | |
| MI1390033 | | | | | | | | |
| MI1390033 | | | | | | | | |
| MI1390033 | | | | | | | 94272 | |
| MI1390033 | | | | | | 44917 | | |
| MI1390033 | | | | 105418 | | | | |
Best Answer
I guess that what you would like is not exactly what you are asking for... so, correct me if I missinterpreted you.
Assuming this is your data (I represent it with a table, but it can be a view):
What you actually want is to flatten these data first.
That is,
GROUP
all rows with the sameID
, and take the only non null value of the other columns (or, if there are more than one, the one value that actually is of interest to you).I have chosen to do this using the
MAX
aggregate function. You may want another one, such asMIN
, or aMIN
||MAX
or something like astring_agg
orgroup_concat
(which MS-SQL Server doesn't yet provide):This would be the intermediate result:
At this point, you can select only the rows with (Letter, pro, record, education) not being null:
You will get:
dbfiddle here
If you're only interested in the
ID
value, but not the rest, you can use a different approach:dbfiddle here