SQL Server 查询基础及分组(每三个小时一组)
一、链接查询
内连接(inner join)。左连接(left join),以左边为基准,全部查询右边没有匹配的值显示为空。右链接(right join),和左连接相反,以右边为基准左边表的字段为空。全链接(full outer join)左右全部连接没有对应值得字段为空。交叉链接(coress join)笛卡尔积
-- inner join 显示 select * from Users inner join Wallets on Users.ID = Wallets.User_ID where Money > 30000 -- inner join 隐式 select * from Wallets,Users where Wallets.User_ID = Users.ID and Money > 10000 -- left join select * from Users left join Wallets on Users.ID = Wallets.User_ID -- right join select * from Wallets right join Users on Users.ID = Wallets.User_ID -- full outer join select * from Users full outer join Wallets on Users.ID = Wallets.User_ID where User_ID is null or Users.ID is null -- cross join select * from Users cross join Wallets where Users.ID = 3
二、from子查询(嵌套查询)
--查询钱包里金额大于30000 select * from Users where exists (select User_ID from Wallets where Money > 30000 and User_ID = Users.ID) select * from Users where ID in (select User_ID from Wallets where Money > 30000)
三、分组
1. 根据日期分组
根据convert 的第一个参数,设置结果的长度达到更具年月分组或年月日分组等
2017-09 长度 7 varchar(7)
2017-09-01 长度10 varchar(10)
-- 使用convert() 函数方式 select convert(varchar(7),CreatTime,120)日期,COUNT(*) 次数,sum(Money)总数 from Orders group by convert(varchar(7),CreatTime,120) -- 先查出对应的年月日等时间,再根据查询出的字段分组 select YEAR(CreatTime) 年,month(CreatTime) 月,COUNT(*) 次数,sum(Money)总数 from Orders group by month(CreatTime),YEAR(CreatTime) order by 年,月 asc
2. 根据划分时间段进行分组(每三个小时一组)
dataname:返回代表指定日期的指定日期部分的字符串。一个参数代表返回的格式,第二个参数为具体值dw:星期几,qq, q:季度,yy, yyyy:年,mm,m:月,dd、d:日,hh:小时,mi, n:分钟 ss、s:秒,ms:毫秒
select t.number 记录数, CONVERT(varchar(2),t.timeGroup * 3)+':00~'+ CONVERT(varchar(2),t.timeGroup * 3 + 2)+':59' 时间段 from (select datename(hh,CreateTime) /3 timeGroup,COUNT(1) number from ClassOptions group by datename(hh,CreateTime) / 3) t