sql 常用语法

1、with as 递归查询

通过UNION ALL 连接部分。通过连接自身whit as 创建的表达式,它的连接条件就是递归的条件。可以从根节点往下查找,从子节点往父节点查找。只需要颠倒一下连接条件。例如代码中条件改为t.ID = c.ParentId即可

复制代码

with tree as(

--0 as Level 定义树的层级,从0开始

select *,0 as Level

from ClassUnis

where ParentId is null

union all

--t.Level + 1每递归一次层级递增

select c.*,t.Level + 1

from ClassUnis c,tree t

where c.ParentId = t.ID

--from ClassUnis c inner join tree t on c.ParentId = t.ID

)

select * from tree where Author not like'%/%'

2、分页查询

DECLARE @PageNumber AS INT, @RowspPage AS INT

SET @PageNumber = 1

SET @RowspPage = 10

SELECT *

FROM F1_WorkflowApplications

ORDER BY CreationTime

OFFSET (@PageNumber - 1) * @RowspPage ROWS

FETCH NEXT @RowspPage ROWS ONLY;

3、分组统计并合计总数及排序

SELECT isnull([MsgType],'总数'), COUNT(*) AS Total FROM [dbo].[BusinessMessages]

Where [CreationTime]>='2024-01-01'

GROUP BY [MsgType]

WITH ROLLUP

Order by [MsgType] desc

WITH ROLLUP 和 WITH cube

ROLLUPCUBE的区别就是: ROLLUP 只会去统计group by 后面的第一个字段每个分组的小计和第一个字段的总计,而CUBE 统计group by 后面的每一个字段分组的小计和第一个字段的总计

以下举例可进行对比:

SELECT [MsgType],ReceiveUserId, COUNT(*) AS Total FROM [dbo].[BusinessMessages]

Where [CreationTime]>='2024-01-01'

GROUP BY [MsgType],ReceiveUserId

with rollup

Order by [MsgType] desc

SELECT [MsgType],ReceiveUserId, COUNT(*) AS Total FROM [dbo].[BusinessMessages]

Where [CreationTime]>='2024-01-01'

GROUP BY [MsgType] ,ReceiveUserId

WITH cube

Order by [MsgType] desc,ReceiveUserId desc

GROUPING SETS

说明:GROUPING SETS 子句允许你指定多个GROUP BY选项,可以通过一条SELECT语句实现复杂繁琐的多条SELECT语句的查询,并且更加的高效。

GROUPING SETS 的 GROUP BY 子句可以生成一个等效于由多个简单 GROUP BY 子句的 UNION ALL 生成的结果集。

GROUPING SETS 可以生成等效于由简单 GROUP BY、ROLLUP 或 CUBE 操作生成的结果。

举例:

SELECT [MsgType],ReceiveUserId,AppID, COUNT(*) AS Total,sum(cast(ReadTag as int)) as rr FROM [dbo].[BusinessMessages]

Where [CreationTime]>='2024-01-01'

GROUP BY GROUPING SETS(

([MsgType], ReceiveUserId,AppID),

([MsgType], ReceiveUserId),

([MsgType])

)

相关推荐
桃酥40335 分钟前
5、MySQL为什么使用 B+树 来作索引【高频】
数据库·b树·mysql
是阿建吖!1 小时前
【MySQL】基本查询(表的增删查改+聚合函数)
数据库·mysql
小玉起起2 小时前
什么是时序数据库?
数据库·时序数据库
绿龙术士2 小时前
【笔记】SQL进阶教程(第二版)
数据库
Allen_LVyingbo2 小时前
数智读书笔记系列020《快速掌握PostgreSQL版本新特性》简介和读书笔记
数据库·人工智能·笔记·postgresql·健康医疗
海姐软件测试2 小时前
Redis如何保持变量访问的安全?
数据库·redis·面试
CodeCraft Studio3 小时前
Excel处理控件Spire.XLS系列教程:C# 在 Excel 中添加、修改和删除切片器
数据库·c#·excel
百锦再3 小时前
全方位对比oracle18c和oracle 19c
开发语言·网络·数据库·oracle·c#·调试·助手
是阿建吖!3 小时前
【MySQL】表的约束
数据库·mysql
金色暖阳4 小时前
耗时sql分析
数据库·sql