目录
T-SQL 高级查询是指在 T-SQL 中使用的复杂查询,可以用于执行复杂的操作。T-SQL 高级查询包括以下几类:
语法
-- 内连接 SELECT * FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID; -- 左连接 SELECT * FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID; -- 右连接 SELECT * FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID; -- 自连接 SELECT CustomerID, FirstName, LastName FROM Customers INNER JOIN Customers AS C2 ON Customers.CustomerID = C2.CustomerID AND Customers.City = C2.City;
语法
-- 过滤数据 SELECT * FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders WHERE OrderDate > '2023-01-01'); -- 聚合数据 SELECT CustomerID, COUNT(*) AS TotalOrders FROM Orders GROUP BY CustomerID; -- 计算数据 SELECT CustomerID, (SELECT MAX(OrderDate) FROM Orders WHERE Customers.CustomerID = Orders.CustomerID) AS LastOrderDate FROM Customers;
语法
-- 按客户 ID 分组 SELECT CustomerID, COUNT(*) AS TotalOrders FROM Orders GROUP BY CustomerID; -- 按客户 ID 和城市分组 SELECT CustomerID, City, COUNT(*) AS TotalOrders FROM Orders GROUP BY CustomerID, City;
语法
select '保安' + 姓名+ '的基本工资是:' +Convert (varchar(50),基本工资)+'元' from 表单 where 职务='保安' 显示表中 保安的姓名 和基本工资 保安 XX 的基本工资是 4500 元
1.0? ? ? ? select name from 表单? where? datediff(year,出生日,getdate()) <18 输出表中 未满18岁的名字 2.0? ? ? ?select 名字+'同学,现在'+convert(varchar(50),出生,getdate()) +''距离20岁还差+convert(varchar(50),datediff(mm,gatedate(), dateadd(yy,20出生))+月 from 表datediff(yy,出生,getdate()) <20 将查询结果输出为:xx同学,现在xx岁,距离20岁还差xx月 3.0 select * from 表where year(出生)>=1990 and year(出生) <2000 筛选出筛选出90后的学员信息 4.0 统计出班级同年人数个数,输出年份和人数 select year(出生日期) as 年份,count(*)as 人 from 表group by year(出生日期)
1.0 select 组,floor(avg(语文))as 语文平均,floor(avg(数学))as数学平均 from bcnt group by 组 统计出各小组的语文平均分和数学平均分,并以取整(向下取整) 向上的话 floor 改为 ceiling即可
语法格式:
-- 计算总和 SELECT SUM(OrderTotal) AS TotalOrders FROM Orders; -- 计算平均值 SELECT AVG(OrderTotal) AS AverageOrder FROM Orders; -- 计算最大值 SELECT MAX(OrderTotal) AS MaximumOrder FROM Orders; -- 计算最小值 SELECT MIN(OrderTotal) AS MinimumOrder FROM Orders;
1.0? select 组,floor(avg(语文))as 语文平均,floor(avg(数学))as数学平均 from bcnt group by 组 统计出各小组的语文平均分和数学平均分,并以取整 2.0? select top 1 * from bcnt where sex='男' and order by 数学+语文 desc 查询出班级男生两门课总分最高的学员信息 3.0? ? select group,sum(yuwen+shuxue) from bcnt group by group ?having avg(数学)>80 筛选出数学组平均分高于80分的组、语文和数学总分 4.0 select top 3 group as组 , avg(语文) as 语文平均分 , avg(数学) as 数学平均分 from bcnt? group by group order by ?avg(数学) desc 筛选出数学组平均分前3的组、语文和数学平均分