Question

I have a header table( VATLH ) i need to join to multiple tables, i need to join it to vatld, to count the number of data rows, and join it to vldocd to see if it the header is used in a Doc (DOCID)

So i use 2 left joins

SELECT VATLH.periode
      , vatlh.dossierID
      , vldocd.docID
      , COUNT(vatld.vatnum)
  FROM vatlh
       LEFT JOIN vatld
       LEFT JOIN vldocd ON  vldocd.dossierID = vatld.dossierID
                AND VLDOCd.PERIODE = VATLd.PERIODE
                AND vldocd.soort = 0 ON  vatld.dossierID = vatlh.dossierID
                AND vatlh.periode = vatld.periode
 GROUP BY VATLH.periode, vatlh.dossierID, vldocd.docID

But if there are no corresponding rows in the vatld table, the DOCID results null if the result should be a DOCID. When adding a corresponding row, the DOCID has the correct data.

Was it helpful?

Solution

This is because you are joining to vldocd using the vatld fields - instead, use the vatlh fields, like so:

SELECT VATLH.periode
      , vatlh.dossierID
      , vldocd.docID
      , COUNT(vatld.vatnum)
  FROM vatlh
       LEFT JOIN vatld ON  vatld.dossierID = vatlh.dossierID
                AND vatlh.periode = vatld.periode
       LEFT JOIN vldocd ON  vldocd.dossierID = vatlh.dossierID
                AND VLDOCd.PERIODE = VATLh.PERIODE
                AND vldocd.soort = 0 
 GROUP BY VATLH.periode, vatlh.dossierID, vldocd.docID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top