2

I'm looking get two things from a query, given a set of contraints:

  • The first match
  • The total number of matches

I can get the first match by:

SELECT TOP 1
    ID,
    ReportYear,
    Name,
    SignDate,
     ... 
FROM Table
WHERE
     ...
ORDER BY ... //I can put in here which one I want to take

And then I can get the match count if I use

SELECT
    MIN(ID),
    MIN(ReportYear),
    MIN(Name),
    MIN(SignDate),
     ... ,
    COUNT(*) as MatchCount
FROM Table
WHERE
     ...
GROUP BY
     ??? // I don't really want any grouping

I really want to avoid both grouping and using an aggregate function on all my results. This question SQL Server Select COUNT without using aggregate function or group by suggests the answer would be

SELECT TOP 1
    ID,
    ReportYear,
    Name,
    SignDate,
     ... ,
    @@ROWCOUNT as MatchCount
FROM Table

This works without the TOP 1, but when it's in there, @@ROWCOUNT = number of rows returned, which is 1. How can I get essentially the output of COUNT(*) (whatever's left after the where clause) without any grouping or need to aggregate all the columns?

What I don't want to do is repeat each of these twice, once for the first row and then again for the @@ROWCOUNT. I'm not finding a way I can properly use GROUP BY, because I strictly want the number of items that match my criteria, and I want columns that if I GROUPed them would throw this number off - unless I'm misunderstanding GROUP BY.

3 Answers 3

7

Assuming you are using a newish version of SQL Server (2008+ from memory) then you can use analytic functions.

Simplifying things somewhat, they are a way of way of doing an aggregate over a set of data instead of a group - an extension on basic aggregates.

Instead of this:

SELECT
     ... , 
    COUNT(*) as MatchCount
FROM Table
WHERE
     ...

You do this:

SELECT
     ... ,
    COUNT(*) as MatchCount OVER (PARTITION BY <group fields> ORDER BY <order fields> )
FROM Table
WHERE
     ...
GROUP BY

Without actually running some code, I can't recall exactly which aggregates that you can't use in this fashion. Count is fine though.

4
  • So can I use it without PARTITIONing or ORDERing? Or somehow put something in the PARTITION BY <> that doesn't change the results (doesn't really group)?
    – Ehryk
    Commented May 4, 2012 at 7:30
  • 1
    Well the point of the partition is to group the data. But group it withing a single record. Withing grouping (partition by) and/or sorting you just have a standard agregate anyway. For the MS documentation look here: msdn.microsoft.com/en-us/library/ms189461.aspx For your first example you can get the first record in a group, for which you sort appropriately, and return the first record. (ie same as doing a "top 1" with an "order by"). What you can't do is use the GROUP clause (if you want to do that as well you need to use a sub query). Commented May 4, 2012 at 10:58
  • Your example worked perfectly as I wanted when combined with @Tom's answer of an empty OVER - COUNT(*) as MatchCount OVER () FROM ...
    – Ehryk
    Commented May 4, 2012 at 16:46
  • This COUNT and PARTITION combo worked well for what I needed on sql server 2005 also - I used it for COUNT and SUM.
    – Nikki9696
    Commented Jul 11, 2012 at 19:11
7

Well, you can use OVER clause, which is an window function.

SELECT  TOP (1)
    OrderID, CustID, EmpID,
    COUNT(*) OVER() AS MatchCount
FROM    Sales.Orders
WHERE   OrderID % 2 = 1
ORDER BY OrderID DESC 
2

Try next query:

select top 1
    *, count(*) over () rowsCount
from
    (
        select
            *, dense_rank() over (order by ValueForOrder) n
        from
            myTable
    ) t
where
    n = 1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.