简体   繁体   中英

SQL Count Number of Occurrences for a Multi-Row Distinct, By Multi-Row Distinct

I have a query that sums all values from the "Total" column and aligns them to their unique combination of storename, year, make, and model (via a Group By):

    select storename, year, make, model, sum(total) as [Sum]
    from #TempTable
    group by storename, year, make, model

An example of the results:

    StoreA 2009 TOYO    AVALON  1039.95
    StoreB 2005 CHET    TAHOE   1039.99
    StoreC 2010 MAZD    CX-9    1040.07
    StoreD 2007 DODG    CHARGER 1040.09
    StoreE 2003 ACUT    MDX     1040.17

What I want to do is add another column to this query that counts how many rows exist in each Group. For example, I know there are 5 instances of a 2009 TOYO AVALON at StoreA, but I want the script to figure out how many there are for each unique combination of storename, year, make, model. And I want it displayed as an extra column [CarCount] to the right of [Sum].

There must be a way, but I have not been able to find a solution. Thank you for your help!

Unless I misunderstood, you need the count on the existing grouping. Just use COUNT to get it.

select storename, year, make, model, sum(total) as [Sum], COUNT(1) as CarCount
    from #TempTable
    group by storename, year, make, model

Add count(*) to the query it will count the number of instances in that group

 select storename, year, make, model, sum(total) as [Sum], count(*) carcount 
    from #TempTable
    group by storename, year, make, model

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