Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row count including column values in sql server

Tags:

sql

sql-server

I need to get the row count of a query, and also get the query's columns in one single query. The count should be a part of the result's columns (It should be the same for all rows, since it's the total).

for example, if I do this: select count(1) from table I can have the total number of rows.

If I do this: select a,b,c from table I'll get the column's values for the query.

What I need is to get the count and the columns values in one query, with a very effective way.

For example: select Count(1), a,b,c from table with no group by, since I want the total.

The only way I've found is to do a temp table (using variables), insert the query's result, then count, then returning the join of both. But if the result gets thousands of records, that wouldn't be very efficient.

Any ideas?

like image 647
c-chavez Avatar asked Nov 11 '11 20:11

c-chavez


2 Answers

@Jim H is almost right, but chooses the wrong ranking function:

create table #T (ID int)
insert into #T (ID)
select 1 union all
select 2 union all
select 3
select ID,COUNT(*) OVER (PARTITION BY 1) as RowCnt from #T
drop table #T

Results:

ID  RowCnt
1   3
2   3
3   3

Partitioning by a constant makes it count over the whole resultset.

like image 146
Damien_The_Unbeliever Avatar answered Nov 15 '22 08:11

Damien_The_Unbeliever


Using CROSS JOIN:

    SELECT a.*, b.numRows
      FROM YOUR_TABLE a
CROSS JOIN (SELECT COUNT(*) AS numRows
              FROM YOUR_TABLE) b
like image 35
OMG Ponies Avatar answered Nov 15 '22 08:11

OMG Ponies