Home > Mobile >  SQL Queries - Count total of rows with Case when statement
SQL Queries - Count total of rows with Case when statement

Time:06-02

I will like to count to get the correct number of rows when the [Location] column match a certain value. Below is my table:

Student Marks Location Date
Kenn 66 UK 09-01-2022
Kenn 89 UK 09-01-2022
Kenn 77 Canada 09-01-2022

Below SQL queries is what I have tried:

  SELECT [Student]
   ,COUNT(CASE WHEN  [Location] = 'UK' THEN [Marks] ELSE 0 END) AS UK
   ,COUNT(CASE WHEN  [Location] = 'Canada' THEN [Marks] ELSE 0 END) AS Canada
  FROM table_name
  GROUP BY [Student]

But the output is

Student UK Canada
Kenn 3 3

What I expected to see is:

Student UK Canada
Kenn 2 1

Please advise if anything wrong with my SQL queries? Thank you!!

CodePudding user response:

Use sum instead

SELECT [Student]
   ,SUM(CASE WHEN  [Location] = 'UK' THEN 1 ELSE 0 END) AS UK
   ,SUM(CASE WHEN  [Device] = 'Canada' THEN 1 ELSE 0 END) AS Canada
  FROM table_name
  GROUP BY [Student]
  • Related