获取每个指定组中结果的第一次出现

时间:2014-10-07 07:48:28

标签: sql sql-server sql-server-2012 ranking-functions

我在sql server 2012中有这个查询

select sum(user_number),
  sum(media_number),
 month_name from (
select TOP 100
    count(distinct a.answer_group_guid) as 'user_number',
  count(distinct a.media_guid) as 'media_number',
 datename(mm,answer_datetime) as 'month_name' ,year(answer_datetime) as 'year'
from
    tb_answers as a
        left outer join
    tb_media as m ON m.user_guid = 'userguid' and m.media_guid=a.media_guid
where
 m.user_guid = 'userguid'

group by concat(year(answer_datetime),'',month(answer_datetime)),datename(mm,answer_datetime),year(answer_datetime)

order by  year(answer_datetime) desc) as aa

group by month_name,year
order by  month_name desc,year desc;

它得到了这个结果 出

user_number  media_number   month_name

5                  1         September

2                  1         October

1                  1         October

1                  1         August

但我只需要第一次出现octuber月

as

user_number  media_number   month_name

5                  1         September

2                  1         October

1                  1         August

1 个答案:

答案 0 :(得分:2)

您只需使用ROW_NUMBER()之类的排名功能即可。使用它来对按month_name分区的记录进行编号,并仅选择每个分区中编号为1的记录,即

将其添加到查询的选择列表中:

ROW_NUMBER() OVER(PARTITION BY month_name ORDER By XXX) as RowNumber

这将对具有相同month_name个连续数字的行进行编号,从1开始,按XXX指定的顺序编号。

注意:在XXX中指定订单以确定哪个月份行是第一个并且将由查询返回

然后,从结果查询中进行选择,按RowNumber = 1

进行过滤
SELECT Q.user_number, Q.media_number, Q.month_name
FROM(
   -- your query + RowNumber) Q
WHERE Q.RowNumber = 1

注意:如果您需要在结果中进行某些排序,则必须将ORDER BY移出子选项,并将其写在WHERE Q.RowNumber=1 旁边