Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Count and Rows in same query

Is it possible to get the total table count and rows in same query. something like this

SELECT COUNT(1),*
FROM tbl
GROUP BY ALL
like image 279
Hary Avatar asked Feb 07 '13 05:02

Hary


People also ask

Can sum and count in same SQL query?

SUM() and COUNT() functions SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can we use GROUP BY and count together in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


2 Answers

You can always try something like this:

SELECT
    COUNT(*) OVER (),
    (list of your other columns here)
FROM dbo.YourTableNameHere

The OVER() clause will give you a count of all rows right in your query.

like image 135
marc_s Avatar answered Sep 29 '22 00:09

marc_s


You can use :

1) select column1,coulmn2,COUNT(*) OVER (PARTITION BY 1) as RowCnt from #Table;

2)Using the cross join method:

SELECT a.*, b.numRows
      FROM TABLE a
CROSS JOIN (SELECT COUNT(*) AS numRows
              FROM TABLE) b
like image 36
user2001117 Avatar answered Sep 28 '22 23:09

user2001117