2014-06-23 73 views
0

我有以下查詢找到軍銜發現排名有兩列甲骨文

SELECT a.appName,RANK() OVER (PARTITION BY a.appName, b.depName ORDER BY a.appName) 
as RANK,b.depName,Count(distinct a.userName) as visitors FROM tbl_app_webstats a 
inner join tbl_users b on b.userName = a.userName 
where a.date_time between '01-JUN-12' and '20-JUN-14' and a.appName like '%' 
group by a.appName,b.depName order by a.appName; 

,但它給我不正確的結果

appName   RANK depName visitors 
app1    1  dep1  1 
app1    1  dep2  1 
app1    1  dep3  2 
app2    1  dep1  3 
app2    1  dep2  1 
app2    1  dep3  5 
app3    1  dep2  2 
app3    1  dep5  8 
app4    1  dep1  2 
app4    1  dep5  13 
app5    1  dep5  2 

結果sholuld是這樣

appName   RANK depName visitors 
app1    1  dep1  1 
app1    2  dep2  1 
app1    3  dep3  2 
app2    1  dep1  3 
app2    2  dep2  1 
app2    3  dep3  5 
app3    1  dep2  2 
app3    2  dep5  8 
app4    1  dep1  2 
app4    2  dep5  13 
app5    1  dep5  2 

任何想法這裏可能是錯的?

回答

1

試試下面的查詢:

SELECT a.appName, 
RANK() OVER (PARTITION BY a.appName ORDER BY b.depName) 
as RANK, 
b.depName,Count(distinct a.userName) as visitors FROM tbl_app_webstats a 
inner join tbl_users b on b.userName = a.userName 
where a.date_time between '01-JUN-12' and '20-JUN-14' and a.appName like '%' 
group by a.appName,b.depName order by a.appName; 

編輯:要獲得前10名的行列

SELECT * FROM 
(
    SELECT a.appName, 
    RANK() OVER (PARTITION BY a.appName ORDER BY b.depName) 
    as RANK, 
    b.depName,Count(distinct a.userName) as visitors FROM tbl_app_webstats a 
    inner join tbl_users b on b.userName = a.userName 
    where a.date_time between '01-JUN-12' and '20-JUN-14' and a.appName like '%' 
    group by a.appName,b.depName order by a.appName 
) WHERE RANK <=10 
order by appName; 
+0

得益於它的工作是什麼,如果我想找出每個應用排名前10位的部門 – Haider

+0

@Haider:推薦編輯獲得前10名 –

1

也許是這樣的:

SELECT a.appName,RANK() OVER (PARTITION BY a.appName ORDER BY b.depName) 
...... 

你也可以這樣做:

SELECT a.appName,ROW_NUMBER() OVER(PARTITION BY a.appName ORDER BY b.depName) 
...... 

爲了解決您發表評論。你可以做這樣的事情:

WITH CTE 
AS 
(
    SELECT RANK() OVER(PARTITION BY appName ORDER BY depName) AS Rank 
    .... 
) 
SELECT 
    * 
FROM 
    CTE 
WHERE 
    CTE.Rank<=10; 
+0

由於其工作,請參見下面的評論 – Haider

+0

@Haider:更新答案 – Arion

1

希望使用CTE方法TOP 10的手段。 嘗試分區單柱a.appName只有

假設你使用分區兩種欄手段(

app1      dep1  =1st Statement Combination is 1 
app1      dep2  =2nd Statement Combination is 1 
app1      dep3  =3rd Statement Combination is 1 



    With CTE(A_Name,A_Rank,A_DepName,A_Visitor) 
    AS 
    (

    SELECT a.appName,RANK() OVER (PARTITION BY a.appName ORDER BY a.appName) 
    as RANK,b.depName,Count(distinct a.userName) as visitors FROM tbl_app_webstats a 
    inner join tbl_users b on b.userName = a.userName 
    where a.date_time between '01-JUN-12' and '20-JUN-14' and a.appName like '%' 
    group by a.appName,b.depName order by a.appName 
) 
Select * from CTE where A_Rank <=10