SQL Server: How can I use the COUNT clause without GROUPing?

后端 未结 3 1089
猫巷女王i
猫巷女王i 2021-01-15 00:44

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 ma

相关标签:
3条回答
  • 2021-01-15 01:04

    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.

    0 讨论(0)
  • 2021-01-15 01:24

    Try next query:

    select top 1
        *, count(*) over () rowsCount
    from
        (
            select
                *, dense_rank() over (order by ValueForOrder) n
            from
                myTable
        ) t
    where
        n = 1
    
    0 讨论(0)
  • 2021-01-15 01:30

    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 
    
    0 讨论(0)
提交回复
热议问题