Sql server 2005中的分析函数

时间:2010-11-09 09:30:49

标签: sql-server-2005 oracle

我有一个查询,它在ORACLE中有效但在SQL SERVER 2005中不起作用...如何将此查询转换为在SQL SERVER 2005中工作。

select user_name
       , url
       , count(*)
       ,first_value(count(*)) over (partition by user_name 
                                    order by count(*) desc) max_total
from urls
group by user_name, url
order by max_total desc,user_name

结果: alt text

3 个答案:

答案 0 :(得分:2)

由于我的评论很大,我会把它写成答案:(

@tanging这不是很正确,但是有一条正确的路径......也许我已经通过查询解决了这个问题,但我想通过分析函数来解决这个问题....我的查询就是这个

select urls.user_name
       ,urls.url
       ,count(*) ct
       ,max_amount 
from urls
     ,(select user_name
              ,max(amount) max_amount
       from (select user_name
                    ,url
                    ,count(*) amount
             from urls
             group by user_name,url)  t1
       group by user_name) t2
where urls.user_name=t2.user_name
group by urls.user_name,urls.url,max_amount
order by max_amount desc,urls.user_name,ct desc

答案 1 :(得分:1)

@tanging这是测试数据......

create table urls(
user_name varchar2(100),
url varchar2(100)
);


insert into urls
values('mariami','google.com');
insert into urls
values('mariami','google.com');
insert into urls
values('mariami','google.com');
insert into urls
values('giorgi','google.com');
insert into urls
values('giorgi','google.com');
insert into urls
values('giorgi','facebook.com');
insert into urls
values('giorgi','facebook.com');
insert into urls
values('giorgi','facebook.com');
insert into urls
values('giorgi','facebook.com');
insert into urls
values('mariami','facebook.com');
insert into urls
values('a','facebook.com');

我的查询结果是: alt text

您的查询结果是: alt text

答案 2 :(得分:0)

WITH    q AS
        (
        SELECT  user_name, url, COUNT(*) AS cnt
        FROM    urls
        GROUP BY
                user_name, url
        )
SELECT  *
FROM    q qo
CROSS APPLY
        (
        SELECT  TOP 1 cnt
        FROM    q qi
        WHERE   qi.user_name = qo.user_name
        ORDER BY
                cnt DESC
        ) qi