Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL subquery with COUNT help

Tags:

sql

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?

like image 361
thefonso Avatar asked Oct 07 '10 18:10

thefonso


People also ask

How do I count rows in SQL subquery?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows. The above syntax is the general SQL 2003 ANSI standard syntax.

How does count (*) work in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.

Why is Count distinct so slow?

It's slow because the database is iterating over all the logs and all the dashboards, then joining them, then sorting them, all before getting down to real work of grouping and aggregating.

Is CTE more efficient than subquery?

Advantage of Using CTESince CTE can be reusable, you can write less code using CTE than using subquery. Also, people tend to follow the logic and ideas easier in sequence than in a nested fashion. When you write a query, it is easier to break down a complex query into smaller pieces using CTE.


2 Answers

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' 
like image 85
codingbadger Avatar answered Sep 21 '22 19:09

codingbadger


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

like image 21
rugg Avatar answered Sep 19 '22 19:09

rugg