34,499
社区成员




请教下如何从表里面选出某几个字段,比如下面表格,从不同分区里面选出同时含有 广东 和 海南 字段的地方
;with src as
(
select [班级]= '一班', [姓名]= '阿香' union all
select [班级]= '一班', [姓名]= '阿强' union all
select [班级]= '一班', [姓名]= '001' union all
select [班级]= '一班', [姓名]= '002' union all
select [班级]= '一班', [姓名]= '003'
)
,temp as -- 多加一列序号,区分
(
SELECT *,ROW_NUMBER() OVER(PARTITION BY 班级 ORDER BY 姓名) AS id
from src
)
select 班级,[1]as 名字,[2]as 名字,[3]as 名字,[4]as 名字,[5]as 名字
from temp
pivot
(
max(姓名)
for id in([1],[2],[3],[4],[5])
)p
;with t1 as (
select '分区a' 分区, '广东深圳' 城市
union all select '分区a', '广东广州'
union all select '分区a', '湖南长沙'
union all select '分区a', '云南昆明'
union all select '分区a', '海南海口'
union all select '分区b', '海南三亚'
union all select '分区b', '海南海口'
union all select '分区b', '广东广州'
union all select '分区b', '云南昆明'
union all select '分区b','广东深圳'
)
-- 筛选
, temp as
(
select *,row_number()over(partition by 分区 order by 分区)as rn
from t1
where 城市 LIKE '广东%' OR 城市 LIKE '海南%'
)
-- 列转行---1.要填的值:【城市】列的值 2.使用【分区】列下的不同名,作为新的列名
select *
from temp
pivot
(
max(城市) --要填的值
for 分区 in(分区a,分区b) -- 列名
)p
非常非常感谢大家帮助 感谢
查询时限制前两个字符是广东或海南即可。select * from table where 城市 like '广东%' or 城市 like '海南%'
非常感谢感谢回复,请教下还有其他更简单的方法么
select *
from table t1
where (charindex('广东', 城市) > 0 or charindex('海南', 城市) > 0)
and exists
(select * from (
select 分区
from table
where (charindex('广东', 城市) > 0 or charindex('海南', 城市) > 0)
group by 分区
having count(distinct case when charindex('广东', 城市) > 0 then 1 when charindex('海南', 城市) > 0 then 2 else null end) = 2
) t2
where t1.分区 = t2.分区
)
就是从表一里面提取表二的数据