0

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

2
  • 3
    Hint: GROUP BY, with COUNT(). Commented Oct 3, 2016 at 11:50
  • but where come from the columns B and C? Are they dog names? Commented Oct 3, 2016 at 11:51

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This should work in single scan:

SELECT
    BreedID,
    SUM(CASE WHEN Photo1 IS NOT NULL THEN 1 ELSE 0 END)
    + SUM(CASE WHEN Photo2 IS NOT NULL THEN 1 ELSE 0 END) [Count]
FROM Table
GROUP BY BreedID

Comments

1

Use Group By and SUM Of Photo1 and Photo2:

Note: If you wants the output for each dog you have to include DogId in group clause.

;WITH T AS
(
    SELECT          
        BreedId,
        SUM (CASE ISNULL(Photo1,0) WHEN 1 THEN 1 ELSE 0 END) AS Photo1,
        SUM (CASE ISNULL(Photo2,0) WHEN 1 THEN 1 ELSE 0 END) AS Photo2
    FROM TableName
    Group By BreedId
)
SELECT      
    BreedId,
    SUM(Photo1+Photo2) AS TotalPhoto
FROM T

Or Simply

SELECT        
    BreedId,
    SUM (CASE ISNULL(Photo1,0) WHEN 1 THEN 1 ELSE 0 END +  CASE ISNULL(Photo2,0) WHEN 1 THEN 1 ELSE 0 END) AS TotalPhoto       
FROM TableName
Group By BreedId

3 Comments

yes, it's bad idea to use COUNT and ISNULL together. NULL values will be counted in this case
And GROUP BY two fields is also wrong :) You can just check the right answer above :)
OP has mention in requirement for each dog and breed but in example show only breedId, so i have include dog and write note for it
0
SELECT BreedID AS Breed, COUNT(Photo1) + COUNT(Photo2) AS #ofPhotos
FROM Dog
GROUP BY BreedID;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.