AsValeO AsValeO - 2 months ago 6
SQL Question

SQL count of values from different columns

I've got a

Dog
table. Each dog has
Breed
and can have 0 to 2 photos. I need to recieve count of photos of all dogs for each breed: table with
BreedId
and matching
PhotosCount
. So result table should be:

BreedID|PhotosCount
-------------------
1 |3
-------------------
2 |1
-------------------


Dogs

Answer

This should do the trick:

SELECT BreedID AS B, COUNT(Photo1) + COUNT(Photo2) AS C
FROM Dog
GROUP BY BreedID

COUNT aggregate function simply doesn't take into consideration NULL values. If, for a specific BreedID, all values of either Photo1 or Photo2 are NULL, then COUNT returns 0.