views:

121

answers:

3

I have a table

EntryLog(Name String, CheckIn Boolean)

I want to count the number of checkins against each name. How do I write a query to get the result as a single resultset?

+6  A: 
SELECT Name, COUNT(*) FROM EntryLog WHERE CheckIn GROUP BY Name
Sjoerd
+1 beat me to it :)
Adam
+1 Beat me, too.
Brian Hooper
Also note that to get the record count result, use `cursor.moveToFirst()` and then get the number in the first field of the result record: `cursor.getInt(0)`
Brad Hein
@Brad, wouldn't it be `cursor.getInt(1)`? Or better yet, using the `Cursor.getColumnIndex` method
Hamy
@Brad - You sure? Correct me if i am wrong, but I am fairly confident that SELECT NAME, Count(\*) will return 2 fields, one named 'Name' and one named 'Count(\*)'. If this is correct, then calling getInt(0) will attempt to get an integer from the first field, which would be the column named 'Name'. This may/may not throw an error. It seems to me that the OP will want to use `cursor.getString(0)` to get the 'Name' column and `cursor.getInt(1)` to get the count column.
Hamy
@Hamy thank you for catching my mistake. Since two fields are being queried there will be two fields in the cursor. The first field is "Name" and the second is the count which we are after. So you would want `getInt(1)` just as you stated.
Brad Hein
@Brad - cool, glad we agree!
Hamy
+4  A: 

Try:

SELECT COUNT(1) FROM EntryLog WHERE CheckIn = 1 GROUP BY [Name]
Adam
but does it fetch only records where CheckIn is true?
Codevalley
No, but surely you can implement that part yourself? - Does now. The important bit was the aggregation via the Group By IMHO.
Adam
+3  A: 
SELECT name,
       COUNT(*)
    FROM EntryLog
    WHERE CheckIn
    GROUP BY name;
Brian Hooper