代码之家  ›  专栏  ›  技术社区  ›  Niko Gamulin

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

sql
  •  2
  • Niko Gamulin  · 技术社区  · 14 年前

    SQL表由列组成 calling_party , called_party call_duration . 示例记录如下:

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

    召集方 我想做一些统计,例如,传入会话的总持续时间是多少,传出会话的数量是多少等等。

    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 回复  |  直到 8 年前
        1
  •  1
  •   Johann Blais    14 年前

    像那样?

    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