I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):
Example db:
RowId Status MemberIdentifier
----- ------ ----------------
1 In Progress 111111111
2 Complete 123456789
3 Not Started 146782452
4 Complete 111111111
5 Complete 123456789
6 Not Started 146782452
7 Complete 111111111
Desired Result:
Status MemberIdentifierCount
------ ----------------------
Not Started 1
In Progress 1
Complete 1
In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).
The DISTINCT keyword with the COUNT function in the SELECT query displays the number of unique data of the field from the table. The Syntax of Count Function With DISTINCT keyword is given below: SELECT COUNT(DISTINCT (Column_Name) FROM table_name WHERE [condition];
To count distinct values, you can use distinct in aggregate function count(). The result i3 tells that we have 3 distinct values in the table.
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns.
Per MemberIdentifier find the status you consider appropriate, e.g. 'In Progress'
wins over 'Complete'
and 'Not Started'
. 'Not Started'
wins over 'Complete'
. Use conditional aggregation for this.
select status, count(*)
from
(
select
case when sum(status = 'In Progress') > 0 then 'In Progress'
when sum(status = 'Not Started') > 0 then 'Not Started'
else 'Complete'
end as status
from mytable
group by memberidentifier
) statuses
group by status;
SELECT max_status AS Status
, COUNT(*) AS ct
FROM (
SELECT MAX(Status) AS max_status
FROM tbl
GROUP BY MemberIdentifier
) AS a
GROUP BY max_status;
This takes advantage of how these strings compare: "In Progress" > "Complete". In doing so, it does random things to any other member with multiple Statuses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With