当前位置: 代码迷 >> Sql Server >> 怎么判断表中的某个字段必须包含三个值,都包含count就加1。求高手帮助
  详细解决方案

怎么判断表中的某个字段必须包含三个值,都包含count就加1。求高手帮助

热度:66   发布时间:2016-04-27 13:46:29.0
如何判断表中的某个字段必须包含三个值,都包含count就加1。。。求高手帮助!
具体是这样的:

【表A】:
项目名称 部门 
----------------------  
项目1 部门1
项目2 部门1
项目3 部门2

【表B】:
项目名称 专业
----------------------
项目1 专业1
项目1 专业2
项目1 专业3
项目2 专业1


【查询结果】:
部门 项目数 归档数 未归数
------------------------------------------
部门1 2 1 1
部门2 1 0 1



在表B里面,同一个项目,这三个专业(专业1、专业1、专业3)都存在,说明归档了,那么归档数为+1
同时,要和表A中的项目名称关联


这个sql语句不晓得要咋写了。。请大家帮帮忙

------解决方案--------------------
SQL code
create table A(项目名称 varchar(10),部门 varchar(10))insert into a values('项目1', '部门1')insert into a values('项目2', '部门1')insert into a values('项目3', '部门2')create table b(项目名称 varchar(10),专业 varchar(10))insert into b values('项目1', '专业1')insert into b values('项目1', '专业2')insert into b values('项目1', '专业3')insert into b values('项目2', '专业1')goselect t1.* , isnull(t2.cnt , 0) 归档数 , t1.项目数 - isnull(t2.cnt , 0) 未归数from(select m.部门, count(1) 项目数from A m group by 部门) t1 left join(select m.部门,count(1) cnt from a m ,(select 项目名称 from(select distinct 项目名称 from b where 专业 = '专业1'union allselect distinct 项目名称 from b where 专业 = '专业2'union allselect distinct 项目名称 from b where 专业 = '专业3') t group by 项目名称 having count(1) = 3) n where m.项目名称 = n.项目名称 group by m.部门) t2on t1.部门 = t2.部门drop table a , b/*部门         项目数         归档数         未归数         ---------- ----------- ----------- ----------- 部门1        2           1           1部门2        1           0           1(所影响的行数为 2 行)*/
  相关解决方案