使用纯SQL查询计算统计信息

时间:2010-10-26 09:18:45

标签: sql

SQL表由calling_partycalled_partycall_duration列组成。示例记录如下:

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

如果有可能,我宁愿编写一个嵌套查询来计算每个用户的统计信息,而无需使用编程语言编写的自定义方法,但不知道如何操作。有谁知道怎么做?

1 个答案:

答案 0 :(得分: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