SQL分组聚合查询练习(SQL Server和Oracle相似)20190514

先建表

CREATE TABLE [dbo].[orderdt_jimmy](
    [nid] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
    [order_nid] [int] NOT NULL,
    [sku] [varchar](100) NOT NULL,
    [qty] [int] NOT NULL,
    [price] [decimal](12, 2) NULL,
    [amount] [decimal](12, 2) NULL
);
GO

怎么查询每一组的前几个?

select t1.rn,t1.order_nid,t1.sku,t1.qty,t1.price,t1.amount from(
select *,ROW_NUMBER() over(partition by order_nid order by sku) rn from orderdt_jimmy) t1
where t1.rn < 5
order by nid,rn;
go

此时,是以order_nid分组,sku排序,然后查询每一组的前四个,如果小于四个,查询数量不变.

效果图:

这些数据都是我自己随机生成的,是自己练习demo生成的数据.

2015年10月-2016年3月 总计:5个月.
2016年11月-2017年6月 总计:7个月.
2017年7月-2018年4月 总计:9个月.
2018年5月-2018年5月 总计:1个月.
2018年6月-2018年12月 总计:6个月.
2019年1月-2019年12月 总计11个月.
2020年2月-2021年2月 总计13个月.
所有总计:5+7+9+1+6+11+13=52个月(4年4个月).
本人认同二元论.我是理想主义者,现实主义者,乐观主义者,有一定的完美主义倾向.不过,一直都是咸鱼(菜鸟),就算有机会,我也不想咸鱼翻身.(并不矛盾,因为具体情况具体分析)
英语,高等数学,考研,其他知识学习打卡交流QQ群:946556683
原文地址:https://www.cnblogs.com/JimmySeraph/p/10862543.html