SQL subquery with COUNT help

Sql

Sql Problem Overview


I have an SQL statement that works

SELECT * FROM eventsTable WHERE columnName='Business'

I want to add this as a subquery...

COUNT(Business) AS row_count

How do I do this?

Sql Solutions


Solution 1 - Sql

This is probably the easiest way, not the prettiest though:

SELECT *,
    (SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
    FROM eventsTable
    WHERE columnName = 'Business'

This will also work without having to use a group by

SELECT *, COUNT(*) OVER () as RowCount
    FROM eventsTables
    WHERE columnName = 'Business'

Solution 2 - Sql

SELECT e.*,
       cnt.colCount 
FROM eventsTable e
INNER JOIN (
           select columnName,count(columnName) as colCount
           from eventsTable e2 
          group by columnName
           ) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'

-- Added space

Solution 3 - Sql

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

Solution 4 - Sql

Assuming there is a column named business:

SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthefonsoView Question on Stackoverflow
Solution 1 - SqlcodingbadgerView Answer on Stackoverflow
Solution 2 - SqlruggView Answer on Stackoverflow
Solution 3 - SqleumiroView Answer on Stackoverflow
Solution 4 - SqlNoel AbrahamsView Answer on Stackoverflow