DISTINCT COUNT in SELECT CASE SQL - mysql

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;

Related

How do I calculate the difference of two alias for sorting

Considering the following code:
SELECT SUM(w.valor),
SUM(CASE WHEN w.tipo = '+' THEN w.valor ELSE 0 END) AS total_credit,
SUM(CASE WHEN w.tipo = '-' THEN w.valor ELSE 0 END) AS total_debit,
w.clientUNIQUE,
c.client as cclient
FROM wallet AS w
LEFT JOIN clients AS c ON w.clientUNIQUE = c.clientUNIQUE
WHERE w.status='V'
GROUP BY w.clientUNIQUE
ORDER BY total_credit-total_debit
I'm trying to calculate the difference of two aliased calculated values for sorting purposes, but I'm getting the following error:
Reference 'total_credit' not supported (reference to group function)
What am I doing wrong and how can I order results by using the difference value between the two aliases?
You can't refer to columns by their alias in the same select expression, so there are 2 options...
Repeat the expressions in the order by (yuk):
ORDER BY
SUM(CASE WHEN w.tipo = '+' THEN w.valor ELSE 0 END) AS total_credit -
SUM(CASE WHEN w.tipo = '-' THEN w.valor ELSE 0 END) AS total_debit
Or easier on the brain and easier to maintain (DRY), order via a sub query:
select * from (
<your query without the ORDER BY>
) q
ORDER BY total_credit - total_debit

Difference between these two mysql queries

I want to know the difference between these two queries: The first query is giving me all the records and its just fine.
Select * from table1 where tender_id='$tender_id' group by supplier_name
But in the following query I have added a sum(case), but I am not getting the desired output. The first query is showing all the records, but the second query is not showing all the records. What mistake am I making?
select cs.*, tender_id,
SUM(CASE WHEN ifmain = 'Yes' THEN total_inr ELSE 0 END) AS maintotal,
SUM(CASE WHEN ifmain = 'No' THEN total_inr ELSE 0 END) AS subtotal
from table1 cs
where cs.tender_id='$tender_id'
group by cs.supplier_name
I want to know if the second query can display all the records with conditions (tender_id)? or its iterating more?
In standard SQL, a query that includes a GROUP BY clause cannot refer
to nonaggregated columns in the select list that are not named in the
GROUP BY clause.
see (for example) https://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html
MySQL has a an unfortunate (and in my opinion incorrect) default behavior when using a GROUP BY clause. This query would NOT be valid in most SQL databases:
Select * from table1 where tender_id='$tender_id' group by supplier_name
and it would not be valid in MySQL either if the ONLY_FULL_GROUP_BY SQL mode has been enabled.
I strongly recommend you treat all queries using GROUP BY as needing ALL non-aggregating columns in that clause. e.g.
select
cs.supplier_name
, SUM(CASE WHEN ifmain = 'Yes' THEN total_inr ELSE 0 END) AS maintotal
, SUM(CASE WHEN ifmain = 'No' THEN total_inr ELSE 0 END) AS subtotal
from table1 cs
where cs.tender_id='$tender_id'
group by
cs.supplier_name
If you need extra columns then e.g.
select
cs.supplier_name
, tender_id
, SUM(CASE WHEN ifmain = 'Yes' THEN total_inr ELSE 0 END) AS maintotal
, SUM(CASE WHEN ifmain = 'No' THEN total_inr ELSE 0 END) AS subtotal
from table1 cs
where cs.tender_id='$tender_id'
group by
cs.supplier_name
, tender_id
and so on. Of course as you include more columns in the group by clause you may increase the number of rows produced, but that is how GROUP BY should work.

Reduce the number of queries

I have seperate queries but i need to reduce the no so put all in one
select count(applicant_id) as registered from student_application where filter_status=0 AND
select count(applicant_id) as filer_select from student_application where filter_status=1 AND
select count(applicant_id) as filter_reject from student_application where filter_status=2
but this shows some errors
Use CASE expression.
Query
select
count(case when filter_status = 0 then applicant_id else null end) as registered,
count(case when filter_status = 1 then applicant_id else null end) as filer_select,
count(case when filter_status = 2 then applicant_id else null end) as filer_reject
from student_application;
SQL Fiddle
You could also use group_by, with the where clause if you're looking for a subset rather than all possible values of filter_status:
SELECT filter_status, COUNT(*)
FROM student_application
WHERE filter_status in (0, 1, 2)
GROUP BY filter_status;

How to sum varchar column in SQL?

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

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.