日期:2014-05-18 浏览次数:20516 次
create table tb ( id int identity(1,1), uid int, --编号 u_no int, --项目 u_no_sub int, --子项 uname varchar(100) --名称 ) insert into tb(uid,u_no,u_no_sub,uname) select 1,1,1,'dell' union select 1,1,2,'机箱' union select 1,2,1,'HP' union select 1,3,1,'索尼' union select 2,1,1,'神舟' union select 2,2,1,'HP' union select 2,2,2,'机箱' union select 2,3,1,'HP' union select 3,1,1,'宏基' union select 3,2,1,'HP' union select 3,3,1,'联想' union select 3,3,2,'鼠标' union select 4,1,1,'宏基' union select 4,2,1,'HP' union select 4,3,1,'联想' union select 4,3,2,'鼠标' union select 4,3,3,'键盘' union select 5,1,1,'宏基' union select 5,2,1,'长城' union select 5,3,1,'HP' union select 5,3,2,'机箱'
--数据表中内容是这样的: id uid u_no u_no_sub uname ----------- ----------- ----------- ----------- ----------- 1 1 1 1 dell 2 1 1 2 机箱 3 1 2 1 HP 4 1 3 1 索尼 5 2 1 1 神舟 6 2 2 1 HP 7 2 2 2 机箱 8 2 3 1 HP 9 3 1 1 宏基 10 3 2 1 HP 11 3 3 1 联想 12 3 3 2 鼠标 13 4 1 1 宏基 14 4 2 1 HP 15 4 3 1 联想 16 4 3 2 鼠标 17 4 3 3 键盘 18 5 1 1 宏基 19 5 2 1 长城 20 5 3 1 HP 21 5 3 2 机箱 (21 row(s) affected)
------解决方案--------------------
--只有一个子项的 select distinct t.uname from tb t join (select uid,u_no from tb group by uid,u_no having count(*)=1) e on t.uid = e.uid and t.u_no = e.u_no
------解决方案--------------------
--6L是结果二 --结果一如下 --只有一个子项的 select t.* from tb t join (select uid,u_no from tb group by uid,u_no having count(*)=1) e on t.uid = e.uid and t.u_no = e.u_no
------解决方案--------------------
--只要有一个子项的 select a.* from tb a right join ( select uid,u_no from tb group by uid,u_no having (count(1)=1) ) b on a.uid=b.uid and a.u_no=b.u_no /* id uid u_no u_no_sub uname ----------- ----------- ----------- ----------- -------- 3 1 2 1 HP 4 1 3 1 索尼 5 2 1 1 神舟 8 2 3 1 HP 9 3 1 1 宏基 10 3 2 1 HP 13 4 1 1 宏基 14 4 2 1