2010-10-26 408 views
2

SQL表由calling_partycalled_partycall_duration列組成。該示例記錄如下:使用純SQL查詢計算統計信息

A,B,23 
A,C,12 
A,H,90 
B,R,56 
N,B,78 

對於存儲在這兩個角色calling_partycalled_party我想進行統計,例如什麼是呼入通話的總時長每一個用戶,究竟是什麼的數量傳出對話等

要選擇用戶我寫了下面的查詢:

SELECT DISTINCT 
    t1.calling_party 
FROM 
    dbo.monthly_connections AS t1 
INNER JOIN 
    (SELECT called_party 
    FROM dbo.monthly_connections) AS t2 ON t1.calling_party = t2.called_party AS table_users 

從這裏開始,我知道如何在經歷所有返回的行所選擇的編程語言創建一個方法如果可能的話我寧願寫,將計算每個用戶的統計數據,未經書面編程語言自定義方法的幫助下,嵌套查詢,但不知道

SELECT SUM(call_duration), COUNT(*) 
FROM table_users 
WHERE calling_party = current_user 
GROUP BY calling_party 

:和執行的每一行查詢怎麼做。有誰知道該怎麼做?

+0

對不起,但你的疑問混淆比他們澄清更多。例如,'table_users'是否真的有名爲'call_duration'和'calling_party'的列?如果你記錄了表格定義,這將有很大的幫助。 – 2010-10-26 09:30:04

回答

1

這樣的事情?

WITH INCOMING AS (
    SELECT called_party PARTY, SUM(call_duration) INCOMING_TOTAL 
    FROM monthly_connections 
    GROUP BY called_party 
), 
OUTGOING AS (
    SELECT calling_party PARTY, SUM(call_duration) OUTGOING_TOTAL 
    FROM monthly_connections 
    GROUP BY calling_party 
) 
SELECT COALESCE(INCOMING.PARTY,OUTGOING.PARTY) AS PARTY, 
     INCOMING.INCOMING_TOTAL, OUTGOING.OUTGOING_TOTAL 
    FROM INCOMING 
    FULL OUTER JOIN OUTGOING ON OUTGOING.PARTY = INCOMING.PARTY