在 SQL 服务器中按 count() 子句分组

Group by a count() clause in SQL Server

我正在尝试编写一个 SQL 查询,它将 return 一个聚合值列表;但是,我想按其中一个聚合值(计数)对查询进行分组:

select t.Field1, count(distinct(t.Field2), SUM(t.Value1)
from MyTable t
group by t.Field1, count(t.Field2)

我试过将计数放入子查询,然后将整个查询放入子查询并在那里分组。有没有一种不涉及创建临时 table 的方法(我对临时 table 本身没有任何反对意见)。

期望的结果如下所示:

Field1    Count      Sum
----------------------------------------------------    
CAT1      3          19.5
CAT1      2          100
CAT2      2          62

我正在处理的数据如下所示:

Field1    Field2    Field3    Value1
-----------------------------------------------------
CAT1      1         1         5
CAT1      2         1         2.5
CAT1      3         1         12
CAT1      4         2         50
CAT1      5         2         50
CAT2      6         3         50
CAT2      7         3         12

所以,我想根据每个 Field3 的不同 Field2 值的数量进行分组

如果我理解正确,那么下面的内容应该有效。

select Field1 , Count , Sum(Value1)
from
(
    select t.Field1, count(*) as Count, SUM(t.Value1) as Value1
    from MyTable t
    group by t.Field1, t.Field3

)
as t2 
group by Field1, Count