代码之家  ›  专栏  ›  技术社区  ›  Matthew Hait

跨多个表的SQL计数

  •  1
  • Matthew Hait  · 技术社区  · 7 年前

      Table1:        Table2:
    +----+----+    +----+----+
    | x  | y  |    | x  | y  |
    +----+----+    +----+----+
    | 20 | 10 |    | 20 | 10 |
    | 20 | 20 |    | 20 | 20 |
    | 20 | 20 |    | 30 | 20 |
    | 40 | 10 |    +----+----+
    +----+----+
    

    输出:

    +----+----+--------+
    | x  | y  | amount |
    +----+----+--------+
    | 20 | 10 |      2 |
    | 20 | 20 |      3 |
    | 30 | 20 |      1 |
    | 40 | 10 |      1 |
    +----+----+--------+
    

    以下是我当前的查询:

    SELECT x, Y, count(*) AS Amount  FROM Table1 
    UNION ALL
    SELECT X, Y, count(*) AS Amount  FROM Table2 
    GROUP BY x, y;
    

    2 回复  |  直到 7 年前
        1
  •  1
  •   Raging Bull    7 年前

    申请 COUNT() 关于结果 UNION :

    select x,y,count(*) as Amount
    from
    (SELECT x, Y FROM Table1 
     UNION ALL
     SELECT X, Y FROM Table2)temp
    group by x,y
    
        2
  •  0
  •   Jacobm001    7 年前

    我会这样设置:

    select
      d.x
      , d.y
      , sum(d.cnt) as cnt
    from
      (
        select x, y, count(*) as cnt from table1 group by x, y
        union all
        select x, y, count(*) as cnt from table2 group by x, y
      ) d
    group by
      d.x
      , d.y