I am trying to select only rows from the INPUT table which do not have a child - in SQL.The result is in OUTPUT. To make it easier, for now, I am considering only the columns 5H and 6H (the other columns I will do later after I have figured how the code needs to be written). The first part of the code before UNION - inserts only rows which have all columns - 1H thru 6H. Then the second part, after UNION, should make sure that only the columns where 5H is not NULL and 6H is null and which do not have a child in 6H, will be included. But it does not work. (NAME5 appears in the OUTPUT - but NAME5 is a parent for the child NAME6).
The embedded JOIN has this: WHERE v1.[5H] <> v2.[5H] -- to make sure that the row which is a parent will be excluded (i.e. v1.[5H] already exists in OUTPUT for a child row). But something goes wrong. Any idea why? Thank you for your help.
I am working in Excel - vba. I was having problems to copy the code in a readable format - hence I am enclosing the code as a picture as well
What I do not understand, why the issue is with: NAME5 is in output and it should not be there, because its child NAME6 is in OUTPUT. But here it works: the child NAME17 is in OUTPUT but its parent NAME16 is not in the OUTPUT (which is correct). Or NAME2 and NAME3 ... it is correct
the code is:
SQLQuery = _
"SELECT v1.[name], v1.[1H], v1.[2H], v1.[3H], v1.[4H], v1.[5H], v1.[6H]" & _
" FROM [INPUT$] as v1 WHERE v1.[2H] IS NOT NULL and " & _
" v1.[3H] IS NOT NULL AND v1.[4H] IS NOT NULL AND v1.[5H] IS NOT NULL AND v1.[6H] IS NOT NULL " & _
"UNION " & _
"SELECT DISTINCT v1.[name], v1.[1H], v1.[2H], v1.[3H], v1.[4H], v1.[5H], v1.[6H]" & _
" FROM [INPUT$] as v1 " & _
" INNER JOIN " & _
" (SELECT * " & _
" FROM [INPUT$] WHERE [5H] IS NOT NULL AND [6H] IS NULL ) as v2 " & _
" ON v1.[1H] = v2.[1H] and v1.[2H] = v2.[2H] and v1.[3H] = v2.[3H] and v1.[4H] = v2.[4H] " & _
" WHERE v1.[5H] <> v2.[5H] "


