一.截斷字符串
declare @str varchar(100)
set @str='123456'
print substring(@str,1,5); 從1的前面算起截取長度爲5的字符串
print substring(@str,1,5);從1算起截取長度爲5的字符串
print left(@str,5) 從左邊開始截取
print right(@str,5)
print ltrim(@str); 去掉字符串左邊的空格
print rtrim(@str)
二.not 的用法
select * from table where column not in ('a','b','c')
not和between連用時要緊跟在where的後面
select * from table where not column between 10 and 30
not和or 、and連用時要緊跟在它們後面
select * from table where not column like '%a' and not column2 like '%b'
三.分組並算出各分組的合計、平均值、max、min、count
select Username ,sum(number) as a from table group by Username
select Username ,avg(number) as a from table group by Username
select count(distinct sale_date) from cook_sales
對不同用戶的number做合計,然後再按合計數據大小排序
select Username ,sum(number) as a from table group by Username order by sum(number) desc
四.inner join、left join 、right join、full join
student:
class:
inner join(內連接)
方法一
select * from student as s,class as c where s.classid=c.classid
方法二
select * from student as s inner join class c on s.classid=c.classid
select * from student as s inner join class c on s.classid<>c.classid
left join(左連接)
select * from student as s left join class c on s.classid=c.classid
right join(右連接)
select * from student as s right join class c on s.classid=c.classid
full join(全連接)
select * from student as s full join class c on s.classid=c.classid
cross join(交叉連接)
select * from student as s cross join class c
select * from student as s ,class c
條件查詢
select * from student as s cross join class c where s.classid=c.classid
select * from student as s , class c where s.classid=c.classid
(cross join 後的條件只能用where)
五、數據類型轉換
select CONVERT(int, 12.1)
select CONVERT(int, '12.1') 報錯
select CONVERT(int, convert(decimal(8,1),'12.1')) 正確
select CONVERT(varchar(200),GETDATE(),120) 獲取當前時間、設置格式、以字符串形式輸出
六、sql拼接並去重列值
select( select distinct CAST(F_ModuleName as varchar)+',' from Sys_Log where F_ModuleName!='' for xml path('') ) as A
第4段這一部分是參考作者:於亮的博客
在此感謝他,謝謝分享