简体   繁体   中英

Best way to select the total count in all rows

I want to find the total count of rows in SQL Server. Below query returns me 1 in all rows. Can I use sub query to calculate the RowCounts Column? Will this affect the performance?

SELECT *, COUNT(*) AS RowCounts FROM Questions Where GroupID = @GroupID 
GROUP BY QuestionID, QuestionTitle, Option1, Option2, Option3, Option4, Answer, GroupID, Explanation, SubjectID

You need a window function

  SELECT *, COUNT(*) OVER (ORDER BY QuestionID ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS RowCounts 
  FROM Questions

If you just want the total count, you can use this window function:

SELECT q.*, COUNT(*) OVER () AS RowCounts
FROM Questions q
WHERE GroupID = @GroupID ;

Window functions are usually more optimized than a separate JOIN and GROUP BY .

If you wanted to enumerate the output rows, I would recommend ROW_NUMBER() :

SELECT q.*, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS seqnum
FROM Questions q
WHERE GroupID = @GroupID ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM