Need help for a query with COUNT(*) that need to 0

Andre Couture 21 Reputation points
2021-01-27T23:13:39.107+00:00

Hello,

I need to query a table and display a line if an item is found or not.

Here is the query

SELECT NAME, COUNT(*)
FROM TABLERA
WHERE NAME IN ('xxx', 'yyy', 'aaa', 'bbb', 'vvv')
GROUP BY NAME;

What I need is a response that looks a bit like that

xxx 0
yyy 1
aaa 1
bbb 1
vvv 0

So far all I tried only return the row for which there's a match.

SQL Server | Other
{count} votes

Accepted answer
  1. Martin Cairney 2,261 Reputation points
    2021-01-28T00:06:13.003+00:00

    Your answer suggests that some of the values do not exist in the table - so this approach will never be able to generate the rows.

    One method could be to create a temp table with the values you want and then
    LEFT JOIN
    this to the main table:

    SELECT b.NAME,
           COUNT(a.NAME)
    FROM (VALUES ('xxx'),('yyy'),('aaa'),('bbb'),('vvv')) as b(NAME)
    LEFT JOIN TABLERA a ON a.NAME = b.NAME
    GROUP BY b.NAME
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.