Sunday, May 17, 2015

Write a SQL Program to get the Sum value of same column with different conditions.

CREATE TABLE student(id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male');

Query:
-----------------------------------
SELECT SUM(CASE WHEN s.gender = 'Male' THEN 1 ELSE 0 END) AS MaleCount,
SUM(CASE WHEN s.gender = 'Female' THEN 1 ELSE 0 END) AS FemaleCount
FROM
student s;

Output:
------------------------------
MaleCount FemaleCount
4 2

0 comments: