数据库中的格式以下,是个记录明细表,要求对明细表进行按日汇总倒序输出。
用下面的SQL语句可以进行按日汇总并且可以分页输出
DECLARE @Days TABLE
(
日期 DATETIME
)
DECLARE @StartDate datetime='2014-04-05 14:22:20'--汇总的开始日期
DECLARE @EndDate datetime='2015-04-08 15:21:33'--汇总的结束日期
DECLARE @start DATETIME
DECLARE @E2_UserName varchar(100)='CN000001'--用户名
DECLARE @StartID INT=1--分页使用的获得记录的开始ID
DECLARE @EndID INT =15--分页使用的获得记录的结束ID,测试为15条数据
SET @start = CONVERT(VARCHAR, @StartDate, 23 )+' 00:00:00'
WHILE @start <= CONVERT(VARCHAR, @EndDate, 23 )+' 00:00:00'
BEGIN
INSERT INTO @Days VALUES(@start)
SET @start = DATEADD(DAY, 1, @start)
END;
WITH orderList AS (
SELECT ROW_NUMBER() OVER (ORDER BY 日期 DESC)AS Row,--这里规定了是按日期倒序排列
SUM(MD_TuiJianJiang) AS 'MD_TuiJianJiang',
SUM(MD_JianDianJiang) AS 'MD_JianDianJiang',
SUM(MD_RiFenHong) AS 'MD_RiFenHong',
SUM(MD_JiHuo) AS 'MD_JiHuo',
SUM(MD_TGZXJiang) AS 'MD_TGZXJiang',
SUM(MD_LingDaoJiang) AS 'MD_LingDaoJiang',
SUM(MD_ShiChangJiang) AS 'MD_ShiChangJiang',
SUM(MD_Help) AS 'MD_Help',
SUM(MD_Luckly) AS 'MD_Luckly',
SUM(MD_FanBuJiang) AS 'MD_FanBuJiang',
SUM(MD_Month) AS 'MD_Month',
SUM(MD_CheckIN) AS 'MD_CheckIN',
SUM(TOTAL) AS 'TOTAL',
日期
FROM (
SELECT
SUM(ISNULL([MD_TuiJianJiang],0)) AS 'MD_TuiJianJiang',
SUM(ISNULL([MD_JianDianJiang],0)) AS 'MD_JianDianJiang',
SUM(ISNULL([MD_RiFenHong],0)) AS 'MD_RiFenHong',
SUM(ISNULL([MD_JiHuo],0)) AS 'MD_JiHuo',
SUM(ISNULL([MD_TGZXJiang],0)) AS 'MD_TGZXJiang',
SUM(ISNULL([MD_LingDaoJiang],0)) AS 'MD_LingDaoJiang',
SUM(ISNULL([MD_ShiChangJiang],0)) AS 'MD_ShiChangJiang',
SUM(ISNULL([MD_Help],0)) AS 'MD_Help',
SUM(ISNULL([MD_Luckly],0)) AS 'MD_Luckly',
SUM(ISNULL([MD_FanBuJiang],0)) AS 'MD_FanBuJiang',
SUM(ISNULL([MD_Month],0)) AS 'MD_Month',
SUM(ISNULL([MD_CheckIN],0)) AS 'MD_CheckIN',
SUM(ISNULL(MD_TuiJianJiang+MD_RiFenHong+MD_JianDianJiang+MD_JiHuo,0)) AS 'TOTAL',
--ISNULL(DAY(MD_Datetime),DAY(B.日期)) AS 'MD_Datetime',
ISNULL([E2_UserName],@E2_UserName) AS 'E2_UserName',
B.日期
FROM [E2_MoneyDetails]
RIGHT JOIN @Days B ON CONVERT(VARCHAR, MD_Datetime, 23 )+' 00:00:00'=B.日期 AND [E2_UserName]=@E2_UserName
WHERE B.日期 BETWEEN DATEADD(DAY, ⑴, @StartDate) AND @EndDate
GROUP BY B.日期,E2_UserName
) E
GROUP BY 日期
)
SELECT *
FROM orderlist
WHERE Row BETWEEN @StartID AND @EndID
终究的结果样式为