当前位置: 代码迷 >> Sql Server >> 这样的结果如何得到
  详细解决方案

这样的结果如何得到

热度:126   发布时间:2016-04-27 14:07:30.0
这样的结果怎么得到
table1
方剂代码 方剂名称 药物列表
D1 方名1 药1,药2,药3,药4,药5
D2 方名1 药1,药2,药4
D3 方名2 药1,药2,药3,药4,药5
D4 方名4 药1,药2,药3,药4,药5
D5 方名5 药1,药3
.....

要找出2个结果
表格式如下:
方剂名称 药物列表

第一种是:
方剂名称相同,但是药物列表不同的

第二种是:
方剂名称不同,但是药物列表相同的



------解决方案--------------------
SQL code
declare @table1 table (方剂代码 varchar(2),方剂名称 varchar(5),药物列表 varchar(30))insert into @table1select 'D1','方名1','药1,药2,药3,药4,药5' union allselect 'D2','方名1','药1,药2,药4' union allselect 'D3','方名2','药1,药2,药3,药4,药5' union allselect 'D4','方名4','药1,药2,药3,药4,药5' union allselect 'D5','方名5','药1,药3'--1\select 方剂名称,药物列表 from @table1 where 方剂名称 in(select 方剂名称 from @table1 group by 方剂名称 having(count(1)>1))/*方剂名称  药物列表----- ------------------------------方名1   药1,药2,药3,药4,药5方名1   药1,药2,药4*/--2\select 方剂名称,药物列表 from @table1 where 药物列表 in(select 药物列表 from @table1 group by 药物列表 having(count(1)>1))/*方剂名称  药物列表----- ------------------------------方名1   药1,药2,药3,药4,药5方名2   药1,药2,药3,药4,药5方名4   药1,药2,药3,药4,药5*/
------解决方案--------------------

SQL code
select * from A a where exists(select * from A ,a where A.方剂名称=a.方剂名称 and a.药物列表<>b.药物列表)select * from A a where exists(select * from A ,a where A.方剂名称<>a.方剂名称 and a.药物列表=b.药物列表)
------解决方案--------------------
SQL code
--table1--方剂代码 方剂名称 药物列表--D1 方名1 药1,药2,药3,药4,药5--D2 方名1 药1,药2,药4--D3 方名2 药1,药2,药3,药4,药5--D4 方名4 药1,药2,药3,药4,药5--D5 方名5 药1,药3--.....if OBJECT_ID('tb') is not null drop table tbgo  create table tb(方剂代码 varchar(50),方剂名称 varchar(50),药物列表 varchar(50)) insert into tb  select 'D1', '方名1' ,'药1,药2,药3,药4,药5' union all  select  'D2', '方名1', '药1,药2,药4' union all  select 'D3', '方名2', '药1,药2,药3,药4,药5' union all  select 'D4', '方名4', '药1,药2,药3,药4,药5' union all  select 'D5', '方名5', '药1,药3'   --要找出2个结果--表格式如下:--方剂名称 药物列表--第一种是:--方剂名称相同,但是药物列表不同的 select t.方剂名称,t.药物列表 from tb b left join (select * from tb )t on b.方剂名称=t.方剂名称 and  b.方剂代码<>t.方剂代码 where    b.药物列表<>t.药物列表 --方剂名称                                               药物列表---------------------------------------------------- ----------------------------------------------------方名1                                                药1,药2,药3,药4,药5--方名1                                                药1,药2,药4--(2 行受影响) --第二种是:--方剂名称不同,但是药物列表相同的select distinct(t.方剂名称),t.药物列表 from tb b left join (select * from tb )t on b.药物列表=t.药物列表  and  b.方剂代码<>t.方剂代码 where    b.方剂名称<>t.方剂名称--方剂名称                                               药物列表---------------------------------------------------- ----------------------------------------------------方名1                                                药1,药2,药3,药4,药5--方名2                                                药1,药2,药3,药4,药5--方名4                                                药1,药2,药3,药4,药5--(3 行受影响)
  相关解决方案