Question

I need to count the number of times the term appears only if it does appear.

I have a table built like the following:

document | term
a0000001 | n/a
a0000001 | for
a0000001 | nothing
a0000002 | lux
a0000002 | the
a0000002 | censoring
a0000003 | the
a0000003 | the
a0000003 | and

This query returns the count of the term that appears in each document:

SELECT document, COUNT(term) AS term_count
FROM documentsx
WHERE term="the"
GROUP BY document;

document | term
a000002  | 1
a000003  | 2

And this query tells me if the matching term appears:

SELECT document, SUM(CASE WHEN term='the' THEN 1 ELSE 0 END) AS "the"
FROM documentsx
GROUP BY documents;

document | the
a000001  | 0
a000002  | 1
a000003  | 1

I am looking for a way to combine these two two queries so that I get the following:

document | the
a000001  | 0
a000002  | 1
a000003  | 2

I'm using MariaDB.

Was it helpful?

Solution

I'm not familiar with MariaDB but in SQL Server I was able to use a UNION to get the combined results you wanted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top