SQL 分组 加列 加自编号 自编号限定 分类: SQL Server ...

说明:

(1)日期以年月形式显示:convert(varchar(7),字段名,120) ,

(2)加一列

(3)自编号:

row_number() over(order by 字段名 desc) as RowID

row_number() over(partition by 字段1 order by 字段2) as RowID

(4)自编号的限制(不可直接在WHERE条件中加)


举例说明:

想要达到的效果:按月统计各工种的前5名(以件数为依据)

初始SQL语句:

select sum(Sum_TrueNum) 件数,PickUser_Name 拣货人,convert(varchar(7),PickTime,120) 时间
from V_OutIn_MainTop 
where Brand_ID=66 and ClassReport_Name='出库' and len(PickUser_Name)>0 
and PickTime>='2014-9-1' and PickTime<'2014-12-1'
group by PickUser_Name,convert(varchar(7),PickTime,120)

效果图:


第一步:    加一列

SQL语句:

select 工种='拣货',sum(Sum_TrueNum) 件数,PickUser_Name 拣货人,convert(varchar(7),PickTime,120) 时间
from V_OutIn_MainTop 
where Brand_ID=66 and ClassReport_Name='出库' and len(PickUser_Name)>0 
and PickTime>='2014-9-1' and PickTime<'2014-12-1'
group by PickUser_Name,convert(varchar(7),PickTime,120)

效果图:


第二步:加自编号(按月、按人分组排序)

SQL语句:

select 工种='拣货',row_number() over(partition by convert(varchar(7),PickTime,120) order by sum(Sum_TrueNum) desc)as RowID,
sum(Sum_TrueNum) 件数,PickUser_Name 拣货人,convert(varchar(7),PickTime,120) 时间
from V_OutIn_MainTop 
where Brand_ID=66 and ClassReport_Name='出库' and len(PickUser_Name)>0 
and PickTime>='2014-9-1' and PickTime<'2014-12-1'
group by PickUser_Name,convert(varchar(7),PickTime,120)

效果图:


第三步:自编号限定(只取前几名)

SQL语句:

with rowJianHuo
as
(
select  工种='拣货',row_number() over(partition by convert(varchar(7),PickTime,120) order by sum(Sum_TrueNum) desc)as RowID, 
sum(Sum_TrueNum) 件数,PickUser_Name 拣货人,convert(varchar(7),PickTime,120) 时间
from V_OutIn_MainTop 
where Brand_ID=66 and ClassReport_Name='出库' and len(PickUser_Name)>0 
and PickTime>='2014-9-1' and PickTime<'2014-12-1'
group by PickUser_Name,convert(varchar(7),PickTime,120)
)
select * from rowJianHuo where RowID<6

也可以这样写:

select * from
(
select  工种='拣货',row_number() over(partition by convert(varchar(7),PickTime,120) order by sum(Sum_TrueNum) desc)as RowID, 
sum(Sum_TrueNum) 件数,PickUser_Name 拣货人,convert(varchar(7),PickTime,120) 时间
from V_OutIn_MainTop 
where Brand_ID=66 and ClassReport_Name='出库' and len(PickUser_Name)>0 
and PickTime>='2014-9-1' and PickTime<'2014-12-1'
group by PickUser_Name,convert(varchar(7),PickTime,120)
)a 
where RowID<6

效果图:(数据有点少,所以数据没有变化)


备注:

两个表,结构相同,连成一张表:用

select * from 表1

union all

select * from 表2


版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/Jackerson/p/4631994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值