T-SQL按2个表分组

T-SQL按2个表分组,sql,tsql,group-by,Sql,Tsql,Group By,我的桌子如下所示: 对于每天的每一次,我想得到最频繁的类别。例如,如果有3次拍卖具有唯一的ClosedTime,但每次拍卖的时间均为TimeOfDay=1,其中2次拍卖的类别ID=1,一次拍卖的类别ID=2,我希望得到: TimeOfDay | CategoryId 1 | 1 TimeOfDay | CategoryId 0 | 1 or 3 numberOfSalesInCategory for both is 1 1 | 2

我的桌子如下所示:

对于每天的每一次,我想得到最频繁的类别。例如,如果有3次拍卖具有唯一的ClosedTime,但每次拍卖的时间均为TimeOfDay=1,其中2次拍卖的类别ID=1,一次拍卖的类别ID=2,我希望得到:

TimeOfDay | CategoryId
1         | 1
TimeOfDay | CategoryId
0         | 1 or 3      numberOfSalesInCategory for both is 1
1         | 2           numberOfSalesInCategory is 3
2         | 2           only one category
3         | 4           numberOfSalesInCategory is 2
我已经尝试过按时间和类别分组,但仍然不知道如何为每个时间分组获得顶级类别。我有这个:

select t.TimeOfDay, a.CategoryId, count(a.CategoryId)
numberOfSalesInCategory 
from Auction a
join Time t on t.Id = a.ClosedTime
where IsSuccess = 1
group by t.TimeOfDay, a.CategoryId
对于一些样本数据,结果如下:

TimeOfDay | CategoryId |    numberOfSalesInCategory
0           1               1
1           1               1
1           2               3
2           2               1
0           3               1
3           3               1
3           4               2
因此,对于这些数据,我想得到:

TimeOfDay | CategoryId
1         | 1
TimeOfDay | CategoryId
0         | 1 or 3      numberOfSalesInCategory for both is 1
1         | 2           numberOfSalesInCategory is 3
2         | 2           only one category
3         | 4           numberOfSalesInCategory is 2

您可以将当前语句放在CTE中,用rank()对它们进行排序,然后执行stuff语句

e、 g


从技术上讲,您正在寻找模式。如果多个值都具有相同的频率,则可以有多个模式。如果您愿意任意选择一个,那么使用
行数()
的条件聚合就是解决方案:

select TimeOfDay,
       max(case when seqnum = 1 then CategoryId end) as ModeCategory
from (select t.TimeOfDay, a.CategoryId, count(*) as numberOfSalesInCategory,
             row_number() over (partition by t.TimeOfDay order by count(*) ) as seqnum
      from Auction a join
           Time t
           on t.id = a.ClosedTime
      where a.isSuccess = 1
      group by t.TimeOfDay, a.CategoryId
     ) ta
group by TimeOfDay;