Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

SQL Group by one column, count entries in another

I'm using a sqlite3 database, with a table like this.

|name   |action     |
-------------------------
|john   |run        |
|jim    |run        |
|john   |run        |
|john   |jump       |
|jim    |jump       |
|jim    |jump       |
|jim    |dive       |

I want to get an output like this

|name   |run    |jump   |dive   |
---------------------------------
|john   |2  |1  |0  |
|jim    |1  |2  |1  |

The closest I've come is with this, but I would like to have a single row like above.

SELECT name, action, COUNT(name)
FROM table
GROUP BY name, action

|name   |action |COUNT(name)    |
|john   |run    |2      |
|john   |jump   |1      |
|jim    |run    |1      |
|jim    |jump   |2      |
|jim    |dive   |1      |

Also, I will need to have some WHERE statements in the query as well.

Am I up in the night thinking this will work?

Answer*

Cancel
1
  • Hey mridkash, this is exactly what I was wanting, and thanks for the links and information (teach a man to fish and all that). Testing shows that this executes faster as well.
    – valentine
    Commented Jun 28, 2011 at 17:49