简体   繁体   English

按多行区分的多行区分的SQL计数发生次数

[英]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. 例如,我知道StoreA上有5个2009 TOYO AVALON实例,但是我想让脚本找出商店名称,年份,品牌,型号的每个唯一组合有多少个。 And I want it displayed as an extra column [CarCount] to the right of [Sum]. 我希望它显示为[Sum]右侧的额外列[CarCount]。

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. 只需使用COUNT即可获取。

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 将count(*)添加到查询中,它将计算该组中的实例数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM