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

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;

Related

How to set 0 when the count row display Null?

So, I have this sql:
SELECT program.BilanganTerhad - IFNULL(COUNT(daftarprogram.KodProgram), 0) AS kiraan
FROM program, daftarprogram
WHERE program.KodProgram = daftarprogram.KodProgram
AND daftarprogram.KodProgram = '19'
How can I set the null COUNT() value to 0? For example: 10 - null = null instead of 10 - 0 = 10.
I need the count become 0, not null.
This is value from table1
While this is value from table2
I want to subtract value from table1 and minus with count(kodprogram)
The thing is I want to subtract value from table1 with count(KodProgram) from table2 based on where condition = KodProgram
COUNT() never returns NULL. That said, your query is malformed (in addition to using archaic join syntax. BilanganTerhad is in the SELECT but it is an aggregation query.
Perhaps you intend:
SELECT p.BilanganTerhad - COUNT(*) AS kiraan
FROM program p JOIN
daftarprogram dp
ON p.KodProgram = dp.KodProgram
WHERE dp.KodProgram = '19'
GROUP BY p.BilanganTerhad;

MAX() doesn't return NULL rows from LEFT JOIN

This will return multiple rows:
SELECT w.word_id, w.word_word, w.word_visits, w.word_created_unix, b.bid_per_visit
FROM keywords_words AS w
LEFT JOIN keywords_bids AS b
ON w.word_id = b.bid_word_id WHERE w.word_word LIKE 'an%'
ORDER BY w.word_visits DESC
LIMIT 10
But this will only return rows where there is a bid in keywords_bids:
SELECT w.word_id, w.word_word, w.word_visits, w.word_created_unix, MAX(b.bid_per_visit)
FROM keywords_words AS w
LEFT JOIN keywords_bids AS b
ON w.word_id = b.bid_word_id WHERE w.word_word LIKE 'an%'
ORDER BY w.word_visits DESC
LIMIT 10
How do I get it to return the MAX(b.bid_per_visit) if there is a bid, and zero if there isn't any bids.
Not excluding rows from the original LIKE search basically.
Use coalesce:
...
MAX(coalesce(b.bid_per_visit, 0))
...
Or don't group by and simply:
...
coalesce(b.bid_per_visit, 0)
...
coalesce() returns the first non-null value in its list of values. With left joins, nulls are returned for the joiner table is there's no matching row.
use of IFNULL(MAX(b.bid_per_visit),0) solve your problem which will return 0 if MAX(b.bid_per_visit) is null and return maximum of b.bid_per_visit if its not null.

Getting the count of result respect to a column

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

COUNT evaluate to zero if no matching records

Take the following:
SELECT
Count(a.record_id) AS newrecruits
,a.studyrecord_id
FROM
visits AS a
INNER JOIN
(
SELECT
record_id
, MAX(modtime) AS latest
FROM
visits
GROUP BY
record_id
) AS b
ON (a.record_id = b.record_id) AND (a.modtime = b.latest)
WHERE (((a.visit_type_id)=1))
GROUP BY a.studyrecord_id;
I want to amend the COUNT part to display a zero if there are no records since I assume COUNT will evaluate to Null.
I have tried the following but still get no results:
IIF(ISNULL(COUNT(a.record_id)),0,COUNT(a.record_id)) AS newrecruits
Is this an issue because the join is on record_id? I tried changing the INNER to LEFT but also received no results.
Q
How do I get the above to evaluate to zero if there are no records matching the criteria?
Edit:
To give a little detail to the reasoning.
The studies table contains a field called 'original_recruits' based on activity before use of the database.
The visits tables tracks new_recruits (Count of records for each study).
I combine these in another query (original_recruits + new_recruits)- If there have been no new recruits I still need to display the original_recruits so if there are no records I need it to evalulate to zero instead of null so the final sum still works.
It seems like you want to count records by StudyRecords.
If you need a count of zero when you have no records, you need to join to a table named StudyRecords.
Did you have one? Else this is a nonsense to ask for rows when you don't have rows!
Let's suppose the StudyRecords exists, then the query should look like something like this :
SELECT
Count(a.record_id) AS newrecruits -- a.record_id will be null if there is zero count for a studyrecord, else will contain the id
sr.Id
FROM
visits AS a
INNER JOIN
(
SELECT
record_id
, MAX(modtime) AS latest
FROM
visits
GROUP BY
record_id
) AS b
ON (a.record_id = b.record_id) AND (a.modtime = b.latest)
LEFT OUTER JOIN studyrecord sr
ON sr.Id = a.studyrecord_id
WHERE a.visit_type_id = 1
GROUP BY sr.Id
I solved the problem by amending the final query where I display the result of combining the original and new recruits to include the IIF there.
SELECT
a.*
, IIF(IsNull([totalrecruits]),consents,totalrecruits)/a.target AS prog
, IIf(IsNull([totalrecruits]),consents,totalrecruits) AS trecruits
FROM
q_latest_studies AS a
LEFT JOIN q_totalrecruitment AS b
ON a.studyrecord_id=b.studyrecord_id
;

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/