Question

I am looking for the proper SQl query to pull data from a the database and COUNT the specific rows to come up with a total... here's my table:

------------------------------------------
|name     |App      |Dep       |Sold     |
------------------------------------------
|Joe      |1        |1         |2        |
|Joe      |1        |2         |2        |
|Steve    |1        |1         |1        |
|Steve    |1        |2         |1        |
------------------------------------------

So I need to count the "1" in each column for each name and come up and output the totals like this:

Joe    |  2 App  |  1 Dep  | 0 Sold
Steve  |  2 App  |  1 Dep  | 2 Sold

Anyone have a starting point for me? I'm not sure if i need JOINs or i can just add seperate COUNTs for each column?

Was it helpful?

Solution

SELECT  Name,
        SUM(App = 1) TotalApp,
        SUM(Dep = 1) TotalDep,
        SUM(Sold = 1) TotalSold
FROM    tableName
GROUP   BY Name

App = 1 is a mysql specific syntax which performs boolean arithmetic resulting 1 and 0. To make it more RDBMS friendly, you can use CASE eg. SUM(CASE WHEN App = 1 THEN 1 ELSE 0 END).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top