2015-08-27 34 views
0

我有一個數據庫,我將主要關注兩個表。表1具有emp_id作爲主鍵獲取兩個表中重複項的計數oracle sql

表1存儲每個員工的訪問信息。我負責計數的員工有多少時間進入一個房間..

表1

emp_id time_in time_out, other columns etc 

1111 3:00  3.30  
2222 1:00  1:10 
3333 2:00  2:45 
4444 7:00  5:00 

表2

sequence_no,EMP_ID,時間,訪問類型,其他列等

表2具有多個物品條目

sequence_no, emp_id, time, access type 

10000  1111  3:00 granted 
10221  1111  3:23 granted 
19911  2222  x 
12122  1111  x 
23232  3333 

我寫了sQl query th在顯示器連接的兩個表,
但此刻我想增加一列,無論是總結總條目(由於序列號,我的查詢返回多行)

select e.emp_id,a.sequence_no,count(sequence_no) from employee, access a where e.emp_id = a.emp_id 
group by e.emp_id having count t(1) > 1 

輸出應該看起來像

emp_id, sequence number, time in/out , total_counts 

1111 10000    3:30   5 
1111 12122    3:30   5 
2222 19911    2:20   19 

在結果中,我需要的序列號會導致重複的emp_id,但每個ID的總數應該是相同的;如果你想用不到兩個條目,以過濾那些環境管理計劃

select 
    e.emp_id, 
    a.sequence_no, 
    count(sequence_no) over (partition by e.emp_id) as total_counts 
from employee, access a 
where e.emp_id = a.emp_id 

:如果你想按EMP

select * 
from 
(
    select 
     e.emp_id, 
     a.sequence_no, 
     count(sequence_no) over (partition by e.emp_id) as total_counts 
    from employee, access a 
    where e.emp_id = a.emp_id 
) 
where total_counts >= 2; 

,在Oracle

回答

1

你不需要任何組(我不知道在sqlserver中的語法是否正常)你可以使用keep

select 
    e.emp_id, 
    max(a.sequence_no) keep (dense_rank first order by time desc), --last sequence 
    count(sequence_no) 
from employee, access a 
where e.emp_id = a.emp_id 
group by e.emp_id 
having count(*) > 1; 
+0

謝謝,在我的查詢中我已經完成了(分區通過)聲明錯誤。它正在計算每個單獨的行...這是我有ROW_NUMBER()OVER(分區由e.emp_id ORDER BY e.emp_id DESC)作爲COUNT。感謝您的輸入。 – kume8sit