2014-11-14 47 views
0

我在Oracle數據庫中有一個表,用於存儲對Web應用程序的請求。結構是這樣的:SQL GROUP BY 3列不工作

--------------------------------------- 
DATETIME | USERID  | ACTION 
--------------------------------------- 

我想建立一個查詢,聚合這些請求的日期,用戶和操作在過去30天。我至今是:

SELECT 
    DATETIME, 
    USERID, 
    ACTION, 
    COUNT(*) 
FROM 
    USER_ACTIVITY 
WHERE 
    DATETIME > SYSDATE - 30 
GROUP BY 
    DATETIME, 
    USERID, 
    ACTION 
ORDER BY 
    DATETIME DESC, 
    COUNT(*) DESC 

當我運行此我得到了很多重複的行,如:

-------------------------------------------------- 
DATETIME | USERID  | ACTION  | COUNT 
-------------------------------------------------- 
14-NOV-14  user1  update  2 
14-NOV-14  user1  update  1 
14-NOV-14  user2  update  3 
14-NOV-14  user1  update  1 

有誰知道爲什麼這些都沒有得到捲起成一個單一的數對於每個不同的組合?

回答

3

大概你在日期上有一個時間組件。試試這個:

SELECT trunc(DATETIME) as date, USERID, ACTION, COUNT(*) 
FROM USER_ACTIVITY 
WHERE DATETIME > SYSDATE - 30 
GROUP BY trunc(DATETIME), USERID, ACTION 
ORDER BY DATETIME DESC, COUNT(*) DESC; 

你可能想同樣的想法適用於where條款,除非你想要的部分天:

SELECT trunc(DATETIME) as date, USERID, ACTION, COUNT(*) 
FROM USER_ACTIVITY 
WHERE DATETIME > trunc(SYSDATE) - 30 
GROUP BY trunc(DATETIME), USERID, ACTION 
ORDER BY DATETIME DESC, COUNT(*) DESC;