跨多个表的SQL计数

时间:2017-07-20 17:48:10

标签: sql sql-server-2008 count sum union

我需要找到每个x&组合的唯一组合的出现次数。在两张桌子上。

class MyComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                name: 'Initial State'
            };
            this.click = this.click.bind(this);
        }
        click() {
            this.setState({
                name: 'React Rocks!'
            });
        }
        render() {
        return (
            <div>
            <button onClick = {this.click}>Click Me</button>
            <h1>{this.state.name}</h1>
            </div>
        );
      }
    };

输出:

  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 |
+----+----+--------+

这会创建x&amp;组独特组合的重复实例。收率

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我会设置这样的东西:

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

此解决方案计算两个表中的唯一条目,然后将结果从两个表中一起添加。