Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select COUNT(Value=Value) Possible?

I want to Count all the rows that only have the value I want like this:

SELECT Users.Balance,
       Users.FreeBids,
       COUNT(Bids.Burned = 0) AS 'ActiveBids',
       COUNT(Bids.Burned = 1) AS 'BurnedBids'
FROM   Users
       INNER JOIN Bids
         ON Users.ID = Bids.BidderID
WHERE  Users.ID = 2
GROUP  BY Users.Balance,
          Users.FreeBids  

It says "Invalid Syntax Neat '=' It works perfectly without the '='. How can I count the rows that Burned=1 in them and Burned=0 in them?

Thanks, Dan

like image 418
Danpe Avatar asked Apr 24 '11 22:04

Danpe


People also ask

Can we use COUNT in select query?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

Can we use COUNT (*)?

There sure is! As you've already learned, COUNT(*) will count all the rows in the table, including NULL values. On the other hand, COUNT(column name) will count all the rows in the specified column while excluding NULL values.

Does COUNT (*) include duplicate values?

Count (*) includes duplicate values as well as NULL values. Count (Col1) includes duplicate values but does not include NULL values.


1 Answers

Use a CASE statement

COUNT(CASE WHEN Bids.Burned=0 THEN 1 END) AS 'ActiveBids', 
COUNT(CASE WHEN Bids.Burned=1 THEN 1 END) AS 'BurnedBids'

There is an implicit ELSE NULL. COUNT only counts NOT NULL values so this will give you the result you need.

like image 116
Martin Smith Avatar answered Oct 17 '22 10:10

Martin Smith