Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql restricted count query

I'm not certain how to structure a SQL query to return the number of rows where a column equals certain values.

For instance,

In table myTable, how can I return the count of all the rows where myColumn = "xyz" and where myColumn = "abc"? Is this possible with a single query?

To clarify, say there are 10 rows where myColumn = "xyx" and 7 rows where myColumn = "abc", the query would return something like:

firstCountResult: 10
secondCountResult: 7
like image 348
lok Avatar asked Jun 17 '26 16:06

lok


2 Answers

How about?:

SELECT 
    COUNT(*),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn

This approach also works with other aggregate functions like MIN, MAX, AVG, SUM... You get the aggregate result per the grouped column's value versus across all rows.

--min myDate per myColumn value
SELECT
    MIN(myDate),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn

--sum of myNumericCol per myColumn value
SELECT
    SUM(myNumericCol),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn
like image 116
Corbin March Avatar answered Jun 19 '26 06:06

Corbin March


You want to group the count by mycolumn so you do this

select 
         myColumn, count(*)
from  
         myTable 
where 
         myColumn in ('xyz','abc')
group by 
         myColumn
like image 27
hol Avatar answered Jun 19 '26 05:06

hol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!