求个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;}
[解决办法]
- SQL code
if object_id('A') is not null drop table Agocreate table A( name varchar(10), feiyong varchar(10), Aid int)goinsert into Aselect '家乐福','条码费',1 union allselect '华润','促销政策',2 union allselect '沃尔玛','促销政策',3goif object_id('B') is not null drop table Bgocreate table B( name varchar(10), price varchar(10), num varchar(10), Aid int)goinsert into Bselect '打折','100','无',2 union allselect '赠品','无','10',2 union allselect '打折','300','无',3 union allselect '赠品','无','20',3goselect 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 行受影响)*/