加入三个表计数

时间:2013-11-20 18:30:57

标签: sql

我在SQL Server数据库中有这三个表(Soknad,Prognose和Did):

表Soknad有列:S_ID(键),S_REFNR

表Prognose有列:P_ID(键),P_S_ID

表是否有列:D_ID(键),D_S_ID,Did_Something

Prognose.P_S_ID是Soknad.S_ID的外键。 Did.D_S_ID是Soknad.S_ID的外键。

表格是这样的:

SOKNAD

  S_ID | S_REFNR |
  1    | abc     |
  2    | cbc     |
  3    | sdf     |

PROGNOSE

  P_ID | P_S_ID |
  10   | 1      |
  11   | 2      |

DID

  D_ID | D_S_ID | D_Did_Something |
  100  | 1      | 1               |
  101  | 1      | 1               |
  102  | 1      | 0               |
  103  | 2      | 1               |
  104  | 2      | 1               |

我想加入这些表(如view或select语句)。在Did表中,应返回一列Did_Something列,以及值为1(一)的同一列的计数。 结果应该是:

S_ID | S_REFNR | P_ID | Count_D_Did_Something | Count_D_Did_Something_Is_One |  
1    | abc     | 10   | 3                     | 2                            |  
2    | cbc     | 11   | 2                     | 2                            |  
3    | sdf     |      |                       |                              |  

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

我相信您要做的是连接两个表,并将行与左表匹配的计数放在每个表的不同列中。

这样就可以实现。

select t1.id, count(t2.id) t2_count , count(t3.id) t3_count
from   table1 as t1 
       left outer join table2 as t2 on t2.table1_id = t1.id
       left outer join table3 as t3 on t3.table1_id = t1.id
group by t1.id;

要根据其中一个外部联接表的条件完成所需的计数,您可以这样做,使用派生表...

select t1.id, count(t2.id) t2_count, count(tt2.mCount) Did_SomethingCount, count(t3.id) t3_count
from   table1 as t1 
       left outer join table2 as t2 on t2.table1_id = t1.id
       left outer join (select count(*), table1_id mCount from table2 where Did_Something = 1 group by table1_id) as tt2 on tt2.table1_id = t1.id
       left outer join table3 as t3 on t3.table1_id = t1.id
group by t1.id;

答案 1 :(得分:0)

你走了:

select s.s_id,
       p.p_id, 
       count(d.Did_Something) as Count_D_Did_Something, -- nulls won't be counted 
       sum(CASE WHEN d.Did_Something = 1 THEN 1 ELSE 0 END) as Count_D_Did_Something_is_one
from   Soknad as s 
       left join Prognose as p on p.P_S_ID = s.s_id
       left join Did as d on d.D_S_ID = s.s_id

答案 2 :(得分:0)

这应该只是给出你需要的结果。注意,我只想总结一下,当你想要数量为具有一个的值时,

SELECT S.S_ID, S.REFNR, P.P_ID, COUNT(D.D_DID_SOMETHING) AS COUNT_D_DID_SOMETHING, 
SUM(D_DID_SOMETHING) AS COUNT_D_DID_SOMETHING_IS_ONE
FROM SOKNAD AS S
INNER JOIN PROGNOSE AS P
ON P.P_S_ID = S.S_ID
INNER JOIN DID AS D
ON D.D_S_ID = S.S_ID
GROUP BY S.S_ID, S.REFNR, P.P_ID
相关问题