日期:2014-05-17 浏览次数:20461 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-06 10:58:35
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[T1]
if object_id('[T1]') is not null drop table [T1]
go
create table [T1]([xm] varchar(6),[zb] varchar(4),[sscp] varchar(5),[sl] int,[je] int)
insert [T1]
select '李明','苏州','产品1',50,80 union all
select '李明','苏州','产品2',60,40 union all
select '李明','苏州','产品3',70,100 union all
select '王歆与','广东','产品1',90,80 union all
select '王歆与','广东','产品2',100,40 union all
select '王歆与','广东','产品3',120,100 union all
select '张可','广东','产品1',14,80 union all
select '张可','广东','产品2',67,40 union all
select '张可','广东','产品3',55,100 union all
select '李一天','苏州','产品1',45,80 union all
select '李一天','苏州','产品2',34,40 union all
select '李一天','苏州','产品3',22,100
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename(sscp)+'=max(case when [sscp]='+quotename(sscp,'''')+' then [sl] else 0 end)'
+','+quotename('rankCompany')+'=max(case when [sscp]='+quotename(sscp,'''')+' then [rankCompany] else 0 end)'
+','+quotename('rankGroup')+'=max(case when [sscp]='+quotename(sscp,'''')+' then [rankGroup] else 0 end)'
from (
select * ,rank()OVER(PARTITION BY sscp ORDER BY sl desc ) [rankCompany],RANK()OVER(PARTITION BY zb ORDER BY sl)[rankGroup],(SELECT&nbs