34,873
社区成员
发帖
与我相关
我的任务
分享
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
alter PROCEDURE Proce_Find_listTime_Station
@M01_AreaCode varchar(20),
@M02_LineCode varchar(20),
@months int,
--用来top的变量
@count int
AS
BEGIN
select M08_LostTimeTypeCode,M06_StationCode,sum(OperaFlag) as Losttime into #Cte from P02_LostTime where M01_AreaCode=@M01_AreaCode and M02_LineCode=isnull(@M02_LineCode,M02_LineCode)
and datepart(MM,Currentdate)=@months and M08_LostTimeTypeCode<>'WorkOrder' and M08_LostTimeTypeCode<>'PPAP'
group by M06_StationCode,M08_LostTimeTypeCode
order by Losttime desc
--动态创建临时表 主要是想在这里创建临时表后再根据变量来top 多少条数据,取得数据后再动态行转列!
--但取得数据插入临时表后也只能在内部访问!下面执行动态行转列就访问不了了!
-- declare @sqlmax varchar(max)
-- set @sqlmax='create table #listtime(M08_LostTimeTypeCode varchar(20),M06_StationCode varchar(20),Losttime int);
-- insert #listtime select top '+@months+' * from #Cte; select * from #listtime
--
-- '
-- exec @sqlmax
--
--在下面要执行动态行转列
;with cte as
(
select *,px=sum(Losttime) over (partition by M06_StationCode) from #Cte
)select * into #a from cte order by px desc
declare @sql varchar(max)
select @sql =isnull(@sql + '],[' , '') + M06_StationCode from #a group by M06_StationCode order by min(px) desc
set @sql = '[' + @sql + ']'
exec ('select * from (select M08_LostTimeTypeCode,M06_StationCode,Losttime from #a ) a pivot (max(Losttime) for M06_StationCode in (' + @sql + ')) b')
END
GO
;with cte as
(
select *,px=sum(Losttime) over (partition by M06_StationCode) from #Cte
)select M08_LostTimeTypeCode,M06_StationCode,Losttime into #a from cte order by px desc ,Losttime desc
exec ('select * from #a where M06_StationCode in (select top '+@count+' M06_StationCode from #a group by M06_StationCode) ')
DECLARE @i INT
SET @i=10
SELECT TOP (@i) * FROM dbo.Ta
select M08_LostTimeTypeCode,M06_StationCode,sum(OperaFlag) as Losttime into #Cte
from P02_LostTime
where M01_AreaCode=@M01_AreaCode and M02_LineCode=isnull(@M02_LineCode,M02_LineCode)
and datepart(MM,Currentdate)=@months and M08_LostTimeTypeCode<>'WorkOrder' and M08_LostTimeTypeCode<>'PPAP'
group by M06_StationCode,M08_LostTimeTypeCode
order by Losttime desc
declare @sqlmax varchar(max)
set @sqlmax='create table #listtime(M08_LostTimeTypeCode varchar(20),
M06_StationCode varchar(20),Losttime int);
insert #listtime select top '+ltrim(@months)+' * from #Cte; select * from #listtime'
exec @sqlmax