如何按两列分组?

时间:2018-09-06 15:00:45

标签: sql sql-server

请在下面考虑。我想列出每个用户预订会议室的次数,以及他/她使用了多少个不同的房间:

room  user
----------
1     1    
2     1
3     2
4     3
4     3

所需的输出:

user  reservations   rooms
-------------------------
1     2              2
2     1              1
3     2              1

谁能告诉我该怎么做?

我现在有:

select [user], count(1)
from   [table]
group by [user]

但是,这并不给我房间数。添加其他count()不起作用。

2 个答案:

答案 0 :(得分:3)

您需要一个count ( distinct <column> )的房间

select [user], count(*) as reservations, count(distinct room) as rooms
from   [table]
group by [user]

答案 1 :(得分:0)

对房间使用不同的聚合

  Select  user,  count(*) reservation_ numbr,count(distinct room) as rooms
  from t group by user