行转列PIVOT示例

USE [TUO_DATA]
GO
/****** Object:  View [dbo].[TBM_ShiftTotal]    Script Date: 07/28/2011 13:00:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER VIEW  [dbo].[TBM_ShiftTotal]
AS
 SELECT ProductionDay,Machine_id,Recipe,ISNULL([DAY],0) AS [DAY],ISNULL([Night],0) AS [Night],
       ISNULL([DAY],0)+ISNULL([Night],0) AS DaySubtotal
FROM (SELECT ProductionDay,Shift,Machine_id,Recipe,COUNT(1) AS ShiftCount FROM (SELECT Machine_id,Recipe,
       CASE  
       WHEN  SUBSTRING(CONVERT(VARCHAR(19), Date_time,120),12,8) <  '08:00:00'
       THEN 'Night'
       WHEN SUBSTRING(CONVERT(VARCHAR(19), Date_time,120),12,8)>='08:00:00'
       AND  SUBSTRING(CONVERT(VARCHAR(19), Date_time,120),12,8)<'20:00:00'
       THEN 'Day'
       WHEN SUBSTRING(CONVERT(VARCHAR(19), Date_time,120),12,8)>='20:00:00'
       AND  SUBSTRING(CONVERT(VARCHAR(19), Date_time,120),12,8)<='23:59:59'
       THEN 'Night'       
       END  AS Shift ,
       CASE  
       WHEN  SUBSTRING(CONVERT(VARCHAR(19), Date_time,120),12,8) <  '08:00:00'          
       THEN   CONVERT(VARCHAR(10), DATEADD(DAY,-1,Date_time), 120)
       ELSE
       CONVERT(VARCHAR(10),  Date_time, 120)
       END AS ProductionDay FROM TBM_Record) A
GROUP BY ProductionDay,Shift,Machine_id,Recipe) B
PIVOT
(
 SUM(B.ShiftCount)
 FOR B.Shift IN ([DAY],[Night])  
 ) AS Pvt

你可能感兴趣的:(行转列)