常用的sql语句

1:按状态排序 未提交-->已提交-->已结束 最后按时间倒序排序 (1:提交 2:未提交 3:已结束 )

SELECT * FROM 表名 ORDER BY 
CASE WHEN Status=2 THEN 3 WHEN Status=1 THEN 2 WHEN Status=3 THEN 1 end DESC , 
FLastModifyTime DESC

 2:防止字段有空的情况

CASE WHEN ISNULL(Status,0)=1 THEN '未提交' WHEN ISNULL(Status,0)=2 THEN '已提交' WHEN ISNULL(Status,0)=3 THEN '已结束' END Status,
或者
CASE WHEN Status IS NOT NULL THEN '未知' WHEN Status = 1 THEN '未提交' WHEN Status=2 THEN '已提交' WHEN Status=3 THEN '已结束' END Status,

 3:统计未提交的人数

SUM((CASE WHEN Status IS NOT NULL AND Status=1 THEN 1 ELSE 0 end))

 4:事务

BEGIN TRANSACTION  --开启事务
 BEGIN
   --执行的操作语句
  IF @@ERROR = 0  --没有错误
     COMMIT TRANSACTION  --提交事务
  ELSE
     ROLLBACK TRANSACTION   --事务回滚
  END 

 5:返回第一个不连续的ID

select top 1 AID from (
select A0.fid as AID,A1.fid as BID from 
(SELECT  fid FROM 表) A0
left join (SELECT  fid FROM 表) A1 on A0.fid+1=A1.fid
) t where BID is null order by AID asc

 6:两张表关联查询,表A为主表,A表对B表一对多

--一般效果
 SELECT ID, 姓名,担保姓名 FROM A 
 LEFT JOIN B ON A.ID=B.ID
                                    
 --处理后的效果,先排序A表(按重复的ID分组),查询时每次找最小的FRowIndex显示姓名,否则显示空
SELECT ID,CASE WHEN pr.FRowIndex=1 then 姓名 ELSE '' END 姓名, 担保姓名
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) FRowIndex,* FROM A) pr 
LEFT JOIN B pc ON pr.ID
=pc.ID

 7.将逗号隔开的一个字符串拆分成多列

select FValue=SUBSTRING(FValue+',',number,charindex(',',FValue+',',number)-number)
from t_table ,master..spt_values s
where type='p' and number>0 and substring(','+FValue,number,1)=',' 

 8.将同一个字段拆分为多个字段

 

 

 

 

 

 

 

SELECT PARSENAME(REPLACE(FValue,',','.'), 1) AS FValue,PARSENAME(REPLACE(FValue,',','.'), 2) AS FValue1,PARSENAME(REPLACE(FValue,',','.'), 3) AS FValue2,PARSENAME(REPLACE(FValue,',','.'), 4) AS FValue3,PARSENAME(REPLACE(FValue,',','.'), 5) AS FValue4
 FROM t_table 

 

posted @ 2021-09-17 14:36  ll...ll  阅读(100)  评论(0编辑  收藏  举报