How to sum varchar column in SQL? - mysql

I am a beginner in SQL. I need to sum up the gender column.I mean how many males and how many females are there in a Table.This is what i tried.
SELECT
SUM(CASE WHEN Gender='Female' THEN Gender ELSE 'Null' END)Gender,
SUM(CASE WHEN Gender='Male' THEN Gender ELSE 'Null' END)Gender
FROM EmployeeDetails;
I am getting this error:
Msg 8117, Level 16, State 1, Line 2
Operand data type nvarchar is invalid for sum operator.
So i tried the following query:
Select length(Gender) - length(replace(Gender, ' ', '')) + 1 NumbofWords
from EmployeeDetails
Its showing as length is not a recognized builtin function.
Any help will be appreciated.
Thanks in advance.

SUM + CASE will work, but you need to sum numbers like:
SELECT
SUM(CASE WHEN Gender='Female' THEN 1 ELSE 0 END) AS [FemaleNumber],
SUM(CASE WHEN Gender='Male' THEN 1 ELSE 0 END) AS [MaleNumber]
FROM EmployeeDetails;
SQL Server 2012+
SELECT
SUM(IIF(Gender='Female', 1, 0)) AS [FemaleNumber],
SUM(IIF(Gender='Male', 1, 0)) AS [MaleNumber]
FROM EmployeeDetails;

This is a little bit of an XY solution, given that it produces rows and not columns. But this is more "database-y", and essentially what you have is a PIVOTed version of the following anyway.
You can't add words, but you can count them. So just GROUP BY your Gender column and COUNT:
select Gender, count(*)
from EmployeeDetails
group by Gender

Related

How do I get the sum of each line depending on the team name?

I have a table called data:
And I would like to get the sum of each row as column name, like this:
What is the correct SQL statement I need? I've been trying with CASE or IF but I just don't get the right answer.
You need aggregation :
select
sum(case when team = 'team business' then total_points else 0 end) as total_business,
sum(case when team = 'team tech' then total_points else 0 end) as total_tech
from
data d;

Counting the number of mention depending on sentiment SQL

Apologies if this is a duplicate of anything, I wasn't finding answers which particularly did what I wanted.
I'm trying to write a SQL query which will return the count of rows which contain a positive, negative or neutral sentiment on one of the candidates in the dataset.
Here is a screenshot for reference
Sentiment is one column but the values in it define the tweet to be positive, negative, or neutral. my goal is to have the query return something like this
if anyone could give me an example on how to do this, I'd appreciate!
try using specific COUNT() functions in your query like this.
SELECT name as `Candidate Name`,
COUNT(CASE WHEN sentiment='Negative' THEN 1 END) AS `Negative`,
COUNT(CASE WHEN sentiment='Positive' THEN 1 END) AS `Positive`,
COUNT(CASE WHEN sentiment='Neutral' THEN 1 END) AS `Neutral`,
COUNT(*) AS `Total`
FROM [table]
GROUP BY candidate
I like using IF()'s or CASE WHEN's to solve this type of thing. Pivots are sometimes time consuming to think through.
SELECT
Name as CandidateName,
SUM(IF(Sentiment = 'N', 1, 0)) as Negative,
SUM(IF(Sentiment = 'Y', 1, 0)) as Positive,
SUM(IF(Sentiment = 'N', 1, 0)) as Neutral
COUNT(*) as Total
FROM [TABLE]
GROUP BY
Name
To use t-SQL, or to just use CASE WHEN's, that same code could look like:
SELECT
Name as CandidateName,
SUM(CASE WHEN Sentiment = 'N' THEN 1 ELSE 0 END) as Negative,
SUM(CASE WHEN Sentiment = 'Y' THEN 1 ELSE 0 END) as Positive,
SUM(CASE WHEN Sentiment = 'N' THEN 1 ELSE 0 END) as Neutral
COUNT(*) as Total
FROM [TABLE]
GROUP BY
Name

get count of two table fields in one query

I am trying to get the count of females and males in the gender field of a table.
Is there a way to get the count of each in one query?
Something like:
select * from table count(where gender = 'm') as total_males, count(where gender = 'f') as total_females;
or will it require two queries?
select count(*) from table where gender = 'm';
select count(*) from table where gender = 'f';
This is basically a PIVOT. MySQL does not have a pivot so you can use an aggregate function with a CASE statement to perform this:
select
sum(case when gender = 'm' then 1 else 0 end) Total_Male,
sum(case when gender = 'f' then 1 else 0 end) Total_Female
from yourtable
See SQL Fiddle with Demo
Or using COUNT:
select
count(case when gender = 'm' then 1 else null end) Total_Male,
count(case when gender = 'f' then 1 else null end) Total_Female
from yourtable;
See SQL Fiddle with Demo
Something like this will work:
SELECT SUM(IF(t.gender='m',1,0)) AS total_males
, SUM(IF(t.gender='f',1,0)) AS total_females
FROM mytable t
The "trick" here is that we are using a conditional test to return either a 0 or a 1 for each row, and then adding up the 0's and 1's. To make this a little more clear, I am using the SUM aggregate function rather than COUNT, although COUNT could be used just as easily, though we'd need to return a NULL in place of the zero.
SELECT COUNT(IF(t.gender='m',1,NULL)) AS total_males
, COUNT(IF(t.gender='f',1,NULL)) AS total_females
FROM mytable t
Consider that the two expressions in the SELECT list of this query:
SELECT COUNT(1)
, SUM(1)
FROM mytable t
Will return the same value.
If you want to avoid the MySQL IF function, this can also be done using the ANSI SQL CASE expression:
SELECT SUM( CASE WHEN t.gender = 'm' THEN 1 ELSE 0 END )) AS total_males
, SUM( CASE WHEN t.gender = 'f' THEN 1 ELSE 0 END )) AS total_females
FROM mytable t
select sum(case when gender='m' then 1 else null end) as total_males, sum(case when gender='f' then 1 else null end) as total_females from ...
Should work just fine!
If your only issue is to avoid two queries, you can always write two queries as subselects of one query.
Select (select 1 from dual) as one, (select 2 from dual) as two from dual
This would work for your scenario, too.

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

I have a column 'hour'
I have a column 'kind' (it can be 1,2 or 3)
I'd like to do something like:
SELECT count(id), SUM(hour) as totHour, SUM( IF ( kind = 1, 1, 0 ) ) as countKindOne
or
SELECT count(id), SUM(hour) as totHour, COUNT( IF ( kind = 1 ) ) as countKindOne
But mysql tell me I've an error... what's the error!?
Please see this stackoverflow topic: MySQL SUM IF field b = field a
.. I'm not able to reply this ...
You can use a CASE statement:
SELECT count(id),
SUM(hour) as totHour,
SUM(case when kind = 1 then 1 else 0 end) as countKindOne
you want something like:
SELECT count(id), SUM(hour) as totHour, SUM(kind=1) as countKindOne;
Note that your second example was close, but the IF() function always takes three arguments, so it would have had to be COUNT(IF(kind=1,1,NULL)). I prefer the SUM() syntax shown above because it's concise.
You can also use SUM + IF which is shorter than SUM + CASE:
SELECT
count(id)
, SUM(IF(kind=1, 1, 0)) AS countKindOne
, SUM(CASE WHEN kind=2 THEN 1 ELSE 0 END) AS countKindTwo
There is a slight difference between the top answers, namely SUM(case when kind = 1 then 1 else 0 end) and SUM(kind=1).
When all values in column kind happen to be NULL, the result of SUM(case when kind = 1 then 1 else 0 end) is 0, whereas the result of SUM(kind=1) is NULL.
An example (http://sqlfiddle.com/#!9/b23807/2):
Schema:
CREATE TABLE Table1
(`first_col` int, `second_col` int)
;
INSERT INTO Table1
(`first_col`, `second_col`)
VALUES
(1, NULL),
(1, NULL),
(NULL, NULL)
;
Query results:
SELECT SUM(first_col=1) FROM Table1;
-- Result: 2
SELECT SUM(first_col=2) FROM Table1;
-- Result: 0
SELECT SUM(second_col=1) FROM Table1;
-- Result: NULL
SELECT SUM(CASE WHEN second_col=1 THEN 1 ELSE 0 END) FROM Table1;
-- Result: 0
From MYSQL I solved the problem like this:
SUM(CASE WHEN used = 1 THEN 1 ELSE 0 END) as amount_one,
Hope this helps :D
It is worth noting that you can build upon Gavin Toweys answer by using multiple fields from across your query such as
SUM(table.field = 1 AND table2.field = 2)
You can also use this syntax for COUNT and I am sure other functions as well.

DISTINCT COUNT in SELECT CASE SQL

I have a table of reports that include the fields Case (unique number), ISR (Individual Safety Report - unique number) and YearsOld.
There can be more than one ISR for each Case. I want to count the number of unique Cases within age groups.
This SQL gives me a count of the number of ISRs:
SELECT
COUNT(CASE WHEN `YearsOld` = -2) THEN 1 END) `No Report`,
COUNT(CASE WHEN `YearsOld` BETWEEN 0 AND 5) THEN 1 END) `0 to 5`
COUNT(CASE WHEN `YearsOld` BETWEEN 6 AND 12) THEN 1 END) `6 to 12`
FROM `Demographics`
is there a way to modify this to count the DISTINCT Cases for these Age Groups?
If your "case" variable is unique, you can certainly put the distinct keyword in the SQL CASE syntax directly:
Count(distinct CASE when yearsold between 6 and 12 then case else null end)
That way, each unique value of the case variable is counted only once.
Just a note on column naming, I would suggest not using a word that has meaning in SQL if you have a choice (I.e. use 'case_num' instead of case).
You could use a subquery to filter your demographics table for a single YearsOld field per case, although if that case might have been related to difference ages for different ISR it'll only end up being counted in one bracket (perhaps this is what you want?):
SELECT
... -- as you currently have
FROM (
SELECT `Case`, `YearsOld` from `Demographics` GROUP BY `Case`
) t;
Alternatively, to "count" each "distinct" "case" within each bracket, you do literally that:
SELECT
COUNT(DISTINCT CASE WHEN `YearsOld` = -2 THEN 1 END) `No Report`,
COUNT(DISTINCT CASE WHEN `YearsOld` BETWEEN 0 AND 5 THEN `Case` END) `0 to 5`,
COUNT(DISTINCT CASE WHEN `YearsOld` BETWEEN 6 AND 12 THEN `Case` END) `6 to 12`
FROM Demographics;