如何进行查询以计算两个表

时间:2015-12-13 18:02:26

标签: sql-server

我有三个主要'维护'表和两个子表'table1'和'table2'主表'maintable'包含两列'ID'和'name',如:

 ID    name
....  ......
 1    Khalid
 2     Jone
 3    Steve

并且第一个子表'table1'包含来自'maintable'的't1ID'和'column'以及'ID'(外键),如下所示:

  t1ID    column     ID
 ......  .......   ....
   1      Value      1
   2      Value      1
   3      Value      1
   4      Value      2

并且第二个子表'table2'包含来自'maintable'的't2ID'和'column'以及'ID'(外键),如下所示:

  t2ID    column     ID
 ......  .......   ....
   1      Value     2
   2      Value     1
   3      Value     1
   4      Value     3

我想查询以查找(table1.ID)的计数为A和(table2.ID)的计数为B,如下所示:

 name     A    B
......   ...  ...
khalid    3    2
Jone      1    1
Steve     0    1

3 个答案:

答案 0 :(得分:2)

试试这个:

create table table0 (id int, nm varchar(20));
insert into table0 values (1,'Khalid'),(2,'Jone'),(3,'Steve');

create table table1 (t1id int, col varchar(20), id int);
insert into table1 values 
(1, 'v', 1), (2, 'v', 1), (3, 'v', 1), (4, 'v', 2);

create table table2 (t2id int, col varchar(20), id int);
insert into table2 values
(1, 'v', 2), (2, 'v', 1), (3, 'v', 1), (4, 'v', 3);

示例:http://sqlfiddle.com/#!6/341ff/10

|     nm | A | B |
|--------|---|---|
|  Steve | 0 | 1 |
|   Jone | 1 | 1 |
| Khalid | 3 | 2 |

结果:

F(round,number_of_opponents_remained):
  res = 0
  opp // number_of_opponents_remained
  for i in [1 opp]
    res = max(res, opp/100 + F(round-1,opp - i) )
  return res

答案 1 :(得分:2)

试试这个:

;with cte1 as (
    SELECT ID, COUNT(1) AS Cnt
    FROM table1
    GROUP BY ID
), cte2 as (
    SELECT ID, COUNT(1) AS Cnt
    FROM table2
    GROUP BY ID
)
SELECT m.name, ISNULL(cte1.Cnt, 0) AS A, ISNULL(cte2.Cnt, 0) AS B
FROM maintable m
    LEFT JOIN cte1 ON cte1.ID = m.ID
    LEFT JOIN cte2 ON cte2.ID = m.ID

也可以使用子查询来完成,但我更喜欢CTE(查询更具可读性)。

答案 2 :(得分:2)

试试这个:

select name, 
 (select count(t1.ID) from table1 t1 where t1.ID = main.ID) as A,
 (select count(t2.ID) from table2 t2 where t2.ID = main.ID) as B
from maintable main