all groups > sql server programming > july 2005 >
You're in the

sql server programming

group:

Number of records in a query


Number of records in a query Dan Slaby
7/7/2005 10:00:51 PM
sql server programming:
I'm sure this is a typical braintwister. However, I have a table that tracks
income by resident, source and quarter. I need to determine the total number
of persons who have been employed 6 months or more (>=2 quarters). I use a
quarter number system such as yyyyq (20052). When I run the following query
I get 84 rows:

Select count(residentid), ResidentID
From tblResidentIncome
Where IncomeSourceCode = 'G'
Group By ResidentID
Having count(IncomeSourceCode) >= 2

This query returns all residents who have an incomesourceCode of 'G' for
more than 2 quarters. How can I derive the number of rows returned (84) from
this query as an output parameter? Thanks.

Re: Number of records in a query Uri Dimant
7/8/2005 12:00:00 AM
Dan
See if this helps
USE pubs

DECLARE @RowCount int

EXEC sp_executesql
N'SELECT @RowCount = COUNT(*) FROM authors',
N'@RowCount int OUTPUT',
@RowCount OUTPUT

RAISERROR ('Authors rowcount is %d', 0, 1, @RowCount)





[quoted text, click to view]

Re: Number of records in a query David Gugick
7/8/2005 12:00:00 AM
[quoted text, click to view]

Declare @TotalCount INT

Select
@TotalCount = COUNT(SubTotal)
From (
Select count(au_id) as "SubTotal"
From dbo.titleauthor
Group By au_id
Having Count(au_id) > 1) a

Select @TotalCount



--
David Gugick
Quest Software
www.imceda.com
Re: Number of records in a query Dan Slaby
7/8/2005 9:12:22 AM
David:

Here's the solution based on your suggestion. However, it doesn't work
unless the 'a' is appended to the end. Why is the 'a' necessary?

Declare @RowCount int
SELECT @RowCount = Count(SubTotal)
FROM (SELECT Count(ResidentID) as "SubTotal"
FROM tblResidentIncome
WHERE IncomeSourceCode = 'G'
Group By ResidentID
Having Count(ResidentID) >= 2)a
SELECT @RowCount

Thanks for the help.

Dan

[quoted text, click to view]

Re: Number of records in a query David Gugick
7/8/2005 1:15:36 PM
[quoted text, click to view]

The alias is required (I just used "a" which is a bit meaningless)
because you are referencing columns in a subquery instead of from the
table directly.

--
David Gugick
Quest Software
www.imceda.com
www.quest.com
AddThis Social Bookmark Button