SQL COUNT issue

  • I could use some help with the following COUNT issue.

    Select distinct Model_id,

    COUNT(CASE WHEN Doors = 4 then 1 ELSE NULL END) [4DoorCount],

    COUNT(CASE WHEN Doors = 2 then 1 ELSE NULL END) [2DoorCount]

    FROM Vehicle_Inv

    Results:

    I would like the results all on one row, but can't figure it out

    :

     

  • You want to use SUM and not COUNT

    Select distinct Model_id,
    SUM(CASE WHEN Doors = 4 then 1 ELSE 0 END) [4DoorCount],
    SUM(CASE WHEN Doors = 2 then 1 ELSE 0 END) [2DoorCount]
    FROM Vehicle_Inv
  • Without knowing that the data looks like this would work, depending on what you need you must change the sum to max

    SELECT  Model_id,4DoorCount=SUM(4DoorCount),2DoorCount=SUM(2DoorCount)
    FROM (
    Select distinct Model_id,

    COUNT(CASE WHEN Doors = 4 then 1 ELSE NULL END) [4DoorCount],

    COUNT(CASE WHEN Doors = 2 then 1 ELSE NULL END) [2DoorCount]

    FROM Vehicle_Inv
    )
    GROUP BY Model_id

    What result do you get using this?

    Select distinct Model_id,

    4DoorCount= COUNT(CASE WHEN Doors = 4 then 1 ELSE NULL END)

    2DoorCount= COUNT(CASE WHEN Doors = 2 then 1 ELSE NULL END)

    FROM Vehicle_Inv

    GROUP BY Model_id

    • This reply was modified 5 years, 1 month ago by  ktflash.
  • Many thanks ktflash - worked like charm.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply