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])

)

相关推荐
lucky_syq17 分钟前
Hive SQL和Spark SQL的区别?
hive·sql·spark
m0_7482448327 分钟前
StarRocks 排查单副本表
大数据·数据库·python
C++忠实粉丝38 分钟前
Redis 介绍和安装
数据库·redis·缓存
wmd131643067121 小时前
将微信配置信息存到数据库并进行调用
数据库·微信
是阿建吖!1 小时前
【Linux】基础IO(磁盘文件)
linux·服务器·数据库
凡人的AI工具箱1 小时前
每天40分玩转Django:Django国际化
数据库·人工智能·后端·python·django·sqlite
ClouGence1 小时前
Redis 到 Redis 数据迁移同步
数据库·redis·缓存
m0_748236581 小时前
《Web 应用项目开发:从构思到上线的全过程》
服务器·前端·数据库
苏三说技术1 小时前
Redis 性能优化的18招
数据库·redis·性能优化
Tttian6222 小时前
基于Pycharm与数据库的新闻管理系统(2)Redis
数据库·redis·pycharm