求个sql查询语句解决方法
求个sql查询语句
表A
name feiyong Aid
家乐福 条码费 1
华润 促销政策 2
沃尔玛 促销政策 3
----------------------------------
如果feiyong值是 促销政策 则有表B
name price num Aid
打折 100 无 2
赠品 无 10 2
打折 300 无 3
赠品 无 20 3
-------------------------------------
想要实现如下查询结果 怎么写sql啊?
name feiyong
家乐福 条码费
华润 促销政策:{类型:打折;价格:100;} {类型:赠品;数量:10;}
沃尔玛 促销政策:{类型:打折;价格:300;} {类型:赠品;数量:20;}
------解决方案--------------------
表A
name feiyong Aid
家乐福 条码费 1
华润 促销政策 2
沃尔玛 促销政策 3
----------------------------------
如果feiyong值是 促销政策 则有表B
name price num Aid
打折 100 无 2
赠品 无 10 2
打折 300 无 3
赠品 无 20 3
-------------------------------------
想要实现如下查询结果 怎么写sql啊?
name feiyong
家乐福 条码费
华润 促销政策:{类型:打折;价格:100;} {类型:赠品;数量:10;}
沃尔玛 促销政策:{类型:打折;价格:300;} {类型:赠品;数量:20;}
------解决方案--------------------
- SQL code
if object_id('A') is not null drop table A go create table A ( name varchar(10), feiyong varchar(10), Aid int ) go insert into A select '家乐福','条码费',1 union all select '华润','促销政策',2 union all select '沃尔玛','促销政策',3 go if object_id('B') is not null drop table B go create table B ( name varchar(10), price varchar(10), num varchar(10), Aid int ) go insert into B select '打折','100','无',2 union all select '赠品','无','10',2 union all select '打折','300','无',3 union all select '赠品','无','20',3 go select t1.name,t1.feiyong,isnull( (select case when name='打折' then '{类型:打折;价格:'+price+'} ' when name='赠品' then '{类型:赠品;数量:'+num+'}' end from B where Aid=t1.Aid for xml path('') ),'') from A t1 left join B t2 on t1.Aid=t2.Aid group by t1.Aid,t1.name,t1.feiyong /* name feiyong ---------- ---------- ---------------------------------------------------------------------------------------------------------------- 家乐福 条码费 华润 促销政策 {类型:打折;价格:100} {类型:赠品;数量:10} 沃尔玛 促销政策 {类型:打折;价格:300} {类型:赠品;数量:20} (3 行受影响) */