表名PrtLog,字段为:Fnum,Fuser,Fdata,如下图
图中只列出某一天的一些数据
如何用SQL语句来统计:
1、某一个月Fnum总和最大的前N个用户(Fuser)并列出来?
2、某一个月每天的Fnum总和,显示出来?
------解决思路----------------------
Declare @TmpData Table(
FNum Int,
FUser NVarchar(10),
FDate DateTime)
Declare @BeginDate DateTime,@EndDate DateTime
--1.某一个月Fnum总和最大的前N个用户(Fuser)并列出来
;With T_Max As(
Select ROW_NUMBER() Over(Order By SUM(FNum)) AS RID,FUser,SUM(FNum) As TotalNum
From @TmpData
Where FDate Between @BeginDate And @EndDate
Group By FUser)
Select * From T_Max Where RID <= 10
--2.某一个月每天的Fnum总和,显示出来?
Select CONVERT(Nvarchar(10),FDate,120) As Dates,SUM(FNum) As TotalNum
From @TmpData
Where FDate Between @BeginDate And @EndDate
Group By CONVERT(Nvarchar(10),FDate,120)
------解决思路----------------------
-- 1、某一个月Fnum总和最大的前N个用户(Fuser)并列出来?
select top [N] Fuser,sum(Fnum) 'Fnum'
from PrtLog
where Fdata between '[月初日期]' and '[月末日期]'
group by Fuser
order by sum(Fnum) desc
-- 2、某一个月每天的Fnum总和,显示出来?
select convert(varchar,Fdata,23) 'Fdata',sum(Fnum) 'Fnum'
from PrtLog
where Fdata between '[月初日期]' and '[月末日期]'
group by convert(varchar,Fdata,23)