Not 100% about this, but it's possible the 342 you get to be over a limited number of documents: Canvas Metric Element: Unique count. Also, the documentation seems to mention this default value: https://www.elastic.co/guide/en/kibana/current/canvas-function-reference.html#essql_fn.
From ES-SQL point of view, the first SELECT just retrieves some documents. The second one, on other hand, is running a cardinality
aggregation on reference_
field and does actually count the unique, non-null terms in that field. I would trust the second query, and would look for clues (like the one I mentioned above) on what kind of count does Canvas calculate on what set of documents.