Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - How to count yes and no items

Tags:

sql

sql-server

I am using SQL Server 2008.

I am writing a query where I need to count how many yesses (1) and how many nos (0 or NULL).

SELECT B.Brand, B.BrandID, COUNT(M.ModelID) AS TotalModels
FROM Brands B LEFT JOIN Models M ON B.BrandID = M.BrandID
GROUP BY B.Brand, B.BrandID
ORDER BY B.Brand

There's another field called IsBestValue in the Model table that will be NULL, 0, or 1. I want to be able to count TotalBestValueYes, TotalBestValueNo, and TotalBestValueNULL.

A long time ago...I use to use something like ..

(CASE WHEN IsBestValue = 1 END) // ADD ONE TO TotalBestValueYes
(CASE WHEN IsBestValue = 0 END) // ADD ONE TO TotalBestValueNo
(CASE WHEN IsBestValue = NULL END) // ADD ONE TO TotalBestValueNULL

Is using CASE in the fashion a good idea? Bad idea? Overkill?

Is there are better way to count yesses and nos and NULLs?

like image 845
Evik James Avatar asked Dec 04 '22 20:12

Evik James


1 Answers

I don't see anything wrong with using the CASE like that if this is what you mean.

SELECT  B.Brand,
        B.BrandID,
        COUNT(M.ModelID) AS TotalModels,
        SUM((CASE WHEN M.IsBestValue = 1 THEN 1 ELSE 0 END)) TotalBestValueYes,
        SUM((CASE WHEN M.IsBestValue = 0 THEN 1 ELSE 0 END)) TotalBestValueNo,
        SUM((CASE WHEN M.IsBestValue IS NULL THEN 1 ELSE 0 END)) TotalBestValueNull,
FROM    Brands B
        LEFT JOIN Models M ON B.BrandID = M.BrandID
GROUP BY B.Brand,
        B.BrandID
ORDER BY B.Brand
like image 194
JNappi Avatar answered Dec 08 '22 01:12

JNappi