1.某字段以逗号隔开的id,查出id对应的文字并仍以逗号隔开
结果示例; 11,34,23 查询结果为 李四,赵二,刘武
SELECT
stuff((
select ','+username
from user
where CHARINDEX(','+cast(userid as varchar(10))+',',','+cast(m.chulr as
varchar(100))+',')>0 for xml path('')),1,1,'') AS a
FROM tablem m
where m.isvalid=1

2.多行合成一行,以逗号隔开
select cityName,stuff((select ','+B.Name from CityItemRole A
left join Users as B on A.UserId=B.Id
where A.CityId=Citys.Id FOR xml PATH('')), 1, 1, '') as roleNames
FROM Citys
3.在where处使用别名
列的别名不能在where条件使用,
具体原因:where子句比select子句先执行,在where执行前列的别名还没有生效。
解决:
select * from(
select id,(a+b+c) as num from tablea
)
where num>0
4.在原字段基础上添加或减少内容
update A表 set B=B+'cd' where 条件
如果出现类似错误:数据类型 text 和 varchar 在 add 运算符中不兼容
update A表 set B=CAST(B as varchar)+'cd' where 条件
5.对某个字段排序
1. RANK()
SELECT RANK() OVER(order by up.year desc) AS RN, up.*
FROM tablea up where id=3680

因为出现重复数据,所以year=2018时,RN=5。
2.ROW_NUMBER()
SELECT ROW_NUMBER()OVER (order by up.year desc) AS RN, up.*
FROM tablea up where id=3680

3. DENSE_RANK()
SELECT DENSE_RANK()OVER (order by up.year desc) AS RN, up.*
FROM tablea up where id=3680


1万+

被折叠的 条评论
为什么被折叠?



