Getting the count of result respect to a column - mysql

My
select distinct c.*
from kuponbahis c
join bahis b on b.sonuc = c.secim and b.ID=c.bahis AND c.durum=0
Query is giving the result as;
How can I get the count of results respect to their "kupon" field.
Expected result;
32, 3
33, 2
Thank you.

Group data by kupon and use count function to get the count of particular kupon
select c.kupon,count(*) as count
from kuponbahis c
join bahis b on b.sonuc = c.secim and b.ID=c.bahis AND c.durum=0
group by c.kupon

You need use group by:
select kupon, count(c.id)
from kuponbahis c
join bahis b on b.sonuc = c.secim and b.ID=c.bahis AND c.durum=0
group by 1
Also your origin query looks strange. You use JOIN (wich means INNER JOIN) and don't select any fields from joined table. In this case you can get zero results if your second table has no records to be joined. Maybe you should just remove JOIN statement?

If I understand you requirement correctly, you want to count the number of bahis, but only include rows that has bahis = 24. If so, you can use COUNT and filter the results in the HAVING clause
select c.kupon, count(*) as count
from kuponbahis c
join bahis b
on b.sonuc = c.secim
and b.ID = c.bahis
where
c.durum = 0
group by c.kupon
having count(case when c.bahis = 24 then 1 end) > 0

Related

SELECT query with JOIN returns duplicate of each row

I am running a SELECT query to return addresses in a table associated with a certain "applicant code" and I'd like to join a table to also return (in the same row) the name of that applicant.
Therefore my query as of now is
SELECT a.id, a.created_at, a.updated_at, a.code, a.applicant_code, a.form_code, a.address_line_1, a.address_line_2, a.town_city, a.county_state, a.country, a.post_code, a.start_date, a.end_date, a.type, ap.first_name, ap.last_name
FROM sfs_addresses a
JOIN sfs_personal_details ap ON a.form_code = ap.form_code
WHERE a.form_code = ? AND a.applicant_code = ?
The query works, and I get the right columns and values in each row, but it returns 2 of each so like
ID
===
1
1
2
2
3
3
4
4
If I remove the JOIN it works fine. I have tried adding DISTINCT (makes no difference) I'm lost.
EDIT: Based on this answer and the comments, the OP realized that the JOIN condition should be on applicant_code rather than form_code.
You have duplicates in the second table based on the JOIN key you are using (I question if the JOIN is correct).
If you just want one row arbitrarily, you can use row_number():
SELECT a.*, ap.first_name, ap.last_name
FROM sfs_addresses a JOIN
(SELECT ap.*,
ROW_NUMBER() OVER (PARTITION BY ap.form_code ORDER BY ap.form_code) as seqnum
FROM sfs_personal_details ap
) ap
ON a.form_code = ap.form_code
WHERE a.form_code = ? AND a.applicant_code = ?;
You can replace the columns in the ORDER BY with which result you want -- for instance the oldest or most recent.
Note: form_code seems like an odd JOIN column for a table called "personal details". So, you might just need to fix the JOIN condition.
relation between 2 tables one to many to return non duplicate use distinct
SELECT distinct a.id, a.created_at, a.updated_at, a.code, a.applicant_code, a.form_code, a.address_line_1, a.address_line_2, a.town_city, a.county_state, a.country, a.post_code, a.start_date, a.end_date, a.type, ap.first_name, ap.last_name
FROM sfs_addresses a
JOIN sfs_personal_details ap ON a.form_code = ap.form_code
WHERE a.form_code = ? AND a.applicant_code = ?

Get columns with value 0 on `group by` with `count`

I'm using this query to get the count of rows grouped by cmp2 field but I need to get a column for every cmp2 even if its sum result is 0. I can't get it this way:
SELECT CMP2, COALESCE(count(*), 0) as count
FROM datos_con851_0,
datos_con851_1
WHERE datos_con851_0.REGISTRO = datos_con851_1.REGISTRO
AND SPEEDER = 1
GROUP BY CMP2;
You want a left join, presumably something like this:
SELECT d0.CMP2, count(d1.REGISTRO) as count
FROM datos_con851_0 d0 left join
datos_con851_1 d1
on d0.REGISTRO = d1.REGISTRO AND
d1.SPEEDER = 1 -- just guess this comes from `d1`
GROUP BY d0.CMP2;

SUM case returns value without GROUP BY

When I add SUM around my case select, it returns the summed value without the GROUP BY.
The query I am using, without the SUM, is the following
SELECT CASE WHEN subscription_types.type = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used
INNER JOIN training_sessions ON training_sessions.id = subscription_used.training_session_id
INNER JOIN training_series AS tserie ON tserie.id = training_sessions.training_serie_id
INNER JOIN user_training_session ON user_training_session.training_session_id = training_sessions.id
INNER JOIN subscriptions ON subscriptions.id = subscription_used.subscription_id
INNER JOIN subscription_types ON subscription_types.id = subscriptions.subscription_type_id
WHERE subscription_used.training_session_id = (SELECT training_sessions.id FROM training_sessions WHERE DATE(event_start_date) = #week_2_ago_date AND training_serie_id = 17) AND present=1
GROUP BY subscriptions.id
This query returns the values: 8,7. However, when I put a SUM around the case, it gives me the number 75. 75 is the SUM of the values that are getting returned without the GROUP BY.
Any ideas on how to fix this problem so that the query gives me the correct value (8+7 = 15, 1 row)? Thanks in advance
Group by is implying distinct values based on subscription.id so probably if you take the group by you you will get something like 8,8,8,8,8,7,7,7,7,7 due to the joins and such.
With the group by you only get the distinct values of 8 and 7. When you do sum with the group it will sum all of them though not the 2 distinct.
Most Simple fix that will give you 15:
SELECT SUM(SUBSCRIPTION_USED) FROM (
SELECT CASE WHEN subscription_types.type = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used
INNER JOIN training_sessions ON training_sessions.id = subscription_used.training_session_id
INNER JOIN training_series AS tserie ON tserie.id = training_sessions.training_serie_id
INNER JOIN user_training_session ON user_training_session.training_session_id = training_sessions.id
INNER JOIN subscriptions ON subscriptions.id = subscription_used.subscription_id
INNER JOIN subscription_types ON subscription_types.id = subscriptions.subscription_type_id
WHERE subscription_used.training_session_id = (SELECT training_sessions.id FROM training_sessions WHERE DATE(event_start_date) = #week_2_ago_date AND training_serie_id = 17) AND present=1
GROUP BY subscriptions.id);
Probably a better way to write it in general though.
EDIT: You could also do SUM(DISTINCT CASE......) if you only want to sum distinct values.

Better way to write MySQL sub-query

I have two tables in my MySQL database: allele and locus. I want to know for a given locus how many alleles there are and of those how many have the status Tentative. I currently have the following query with subquery:
SELECT COUNT(*) as alleleCount,
(SELECT COUNT(*)
FROM allele
INNER JOIN locus ON allele.LocusID = locus.PrimKey
WHERE Status = 'Tentative'
AND locus.ID = 762
) as newAlleleCount
FROM allele
INNER JOIN locus ON allele.LocusID = locus.PrimKey
WHERE locus.ID = 762
but I feel there must be a better way to write this query.
You can use SUM() using sum with condition will result in a boolean 1 or 0 so it will give you the count for your conditions
SELECT locus.ID,COUNT(*) `all_alleles_per_locus`,
SUM(Status = 'Tentative') `tentative_alleles_762`
FROM allele
INNER JOIN locus ON allele.LocusID = locus.PrimKey
GROUP BY locus.ID
One way would be to group the locus by its statuses and fetch each status's respective count; using the WITH ROLLUP modifier will add a NULL status at the end representing the total:
SELECT status, COUNT(*)
FROM allele JOIN locus ON locus.PrimKey = allele.LocusID
WHERE locus.ID = 762
GROUP BY status WITH ROLLUP
If you absolutely do not want a list of all statuses, you can instead GROUP BY status = 'Tentative' (optionally WITH ROLLUP if desired)—but it will not be sargable.

Query output differs from the expected output

Below query is doing what I need:
SELECT assign.from_uid, assign.aid, assign.message, curriculum.asset,
curriculum.title, curriculum.description
FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum
ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13 AND assign.status = 1
GROUP BY assign.from_uid, assign.to_uid, assign.nid
ORDER BY assign.created DESC
Now I need to get the total count of rows of the result. For example if it is displaying 5 rows the o/p should be like My expected o/p. The query I tried is given below.
SELECT count(description) FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13 AND assign.status = 1
GROUP BY assign.from_uid, assign.to_uid, assign.nid
ORDER BY assign.created DESC
My expected o/p:
count(*)
---------
5
My current o/p:
count(*)
---------
6
2
5
6
6
The easiest solution would be to
place your initial GROUP BY query in a subselect
select the amount of rows retrieved from this subselect
SQL Statement
SELECT COUNT(*)
FROM (
SELECT assign.from_uid
FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13
AND assign.status = 1
GROUP BY
assign.from_uid
, assign.to_uid
, assign.nid
) q
Edit - why doesn't the original query return the results required
It did already prepared what was needed to get the correct result
Your query without grouping returns a resultset of 25 records (6+2+5+6+6)
From these 25 records, you have 5 unique combinations of from_uid, to_uid, nid
Now you don't want to count how many records each combination has (as you did in your example) but how many unique (distinct anyone?) combinations there are.
One solution to this is the subselect I presented but following equivalent statement using a DISTINCT clause might be more comprehensive.
SELECT COUNT(*)
FROM (
SELECT DISTINCT assign.from_uid
, assign.to_uid
, assign.nid
FROM assignment assign
INNER JOIN curriculum_topics_assets curriculum ON assign.nid = curriculum.asset
WHERE assign.to_uid = 13
AND assign.status = 1
) q
Note that my personal preference goes to the GROUP BY solution.
To get the number of rows for a query do:
SELECT COUNT(*) as RowCount FROM (--insert other query here--) s
In you example:
SELECT COUNT(*) as RowCount FROM (SELECT a.from_uid
FROM assignment a
INNER JOIN curriculum_topics_assets c ON a.nid = c.asset
WHERE a.to_uid = 13
AND a.status = 1
GROUP BY a.from_uid, a.to_uid, a.nid
) s
Note that I the dropped the stuff that has no effect on the number of rows to make the query run slightly faster.
You should use COUNT(*) instead of count(description). Look at: http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/