1

I would like to retrieve total rows and also all values through a stored procedure in SQL Server. I have something like below. However, it mentioned of it is not contained in either an aggregate function or the GROUP BY clause. Appreciate for any reply. Thanks.

ALTER PROCEDURE abc.testing
    @facility varchar(50), 
    @date datetime
AS

SELECT count(*), * 
FROM ss_table 
WHERE _start = @date 
      And fid IN (SELECT id 
                  FROM ss_facilities 
                  WHERE name = @facility)
0

3 Answers 3

1

Try this

SELECT SS.cnt, ss_table.* 
FROM ss_table
     cross apply (SELECT count(*) cnt
                  FROM ss_table 
                  WHERE _start = @date 
                        And fid IN (SELECT id 
                                    FROM ss_facilities 
                                    WHERE name = @facility)                
                 )  ss 
WHERE _start = @date 
      And fid IN (SELECT id 
                  FROM ss_facilities 
                  WHERE name = @facility)
Sign up to request clarification or add additional context in comments.

Comments

1

You need a group clause when using an aggregate function like count. If ss_table has an id column, do the count function on it.

It would work like this:

SELECT count(id), <explicitly define column names except the id here> 
FROM ss_table 
WHERE _start = @date 
And fid IN (SELECT id FROM ss_facilities WHERE name = @facility)
group by <enter every column except the id from ss_table here>

Should work for you.

Comments

0

You can't usefully mix and match aggregate queries and non-aggregate queries - split them up into two separate stored procedures.

(this specific error message is being presented because in order to return columns in an aggregate query, every column must either be in the "group by" fields, or have an aggregate function applied to it ("max", "count", etc). In this query, "*" meets neither of these criteria).

1 Comment

If it wasn't all that clear from my answer, the reason it doesn't allow this is that a query which includes a "count(*)" without a "GROUP BY" clase wants to return a single row for the group of all input rows, whereas "select *" wants to return all of the underlying rows. Apart from anything else, the result format for both of these queries is different - the former being a simple count, the latter being the format of the underlying data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.