日期:2014-05-17 浏览次数:20377 次
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[testtb](
[fEmployee] [nvarchar](50) NULL,
[fSalery] [numeric](18, 2) NULL,
[fDate] [date] NULL
) ON [PRIMARY]
GO
INSERT INTO testtb
SELECT '张三',12452,GETDATE()
UNION
SELECT '历史',5262,GETDATE()
UNION
SELECT '咖啡机',23511,GETDATE()
UNION
SELECT '大锅饭',5231,GETDATE()
UNION
SELECT '张三',63263,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '历史',2363,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '咖啡机',1552,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '大锅饭',43733,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '说的',26363,GETDATE()
UNION
SELECT '第三方',562,GETDATE()
UNION
SELECT '阿什顿',211,GETDATE()
UNION
SELECT '单身档',5131,GETDATE()
UNION
SELECT '说的',263,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '第三方',23163,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '阿什顿',15652,DATEADD(MONTH,-1,GETDATE())
UNION
SELECT '单身档',433,DATEADD(MONTH,-1,GETDATE())
SELECT TOP 5 a.fEmployee,
SUM(CASE a.fDate WHEN CONVERT(DATE,DATEADD(MONTH,-1,GETDATE()))
then a.fSalery ELSE 0 END)
八月薪水,
SUM(CASE a.fDate WHEN CONVERT(DATE,GETDATE())
then a.fSalery ELSE 0 END)
九月薪水
,SUM(CASE a.fDate WHEN CONVERT(DATE,DATEADD(MONTH,-1,GETDATE()))
then a.排名 ELSE 0 END) 八月排名,
SUM(CASE a.fDate WHEN CONVERT(DATE,GETDATE())
then a.排名 ELSE 0 END) 九月排名,
SUM(CASE a.fDate WHEN CONVERT(DATE,DATEADD(MONTH,-1,GETDATE()))
then a.排名 ELSE 0 END)-SUM(CASE a.fDate WHEN CONVERT(DATE,GETDATE())
then a.排名 ELSE 0 END) 排名变动
FROM
(
SELECT a.fEmployee,a.fDate,a.fSalery
,rank() over(partition by a.fDate order by a.fSalery desc) 排名