我遇到了一个问题,那就是在两个没有直接关系的表之间创建交叉表。这是我的表
员工 - 包含员工数据
出勤 - 包含日,夜,午夜,EmpID,从 - 日期
EmpWages - 包含工资,FromDate
交叉表应该在考勤和& EmpWages表
From-Date 1 ............ From-Date N(EmpWages)
白天,夜晚,午夜...........日,夜,午夜(出勤)
请帮帮我
答案 0 :(得分:0)
这就是我所做的。
USE [FPR]
GO
/****** Object: StoredProcedure [dbo].[GAD] Script Date: 01/26/2012 18:38:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GAD]
As
DECLARE @ReportColumnNames NVARCHAR(max)
DECLARE @SQLtext NVARCHAR(max)
SELECT @ReportColumnNames = Stuff( (
SELECT ', ' + QUOTENAME(YYYY) AS [text()]
FROM (SELECT DISTINCT YYYY=CAST(FromDate As Date)
FROM dbo.EmpWages ) x
ORDER BY YYYY
FOR XML PATH ('')), 1, 1, '')
SELECT @SQLtext = N'SELECT SNo=IDENTITY(int,1,1), * INTO #temp_t FROM (SELECT
(FromDate) AS OYe, Days = (
CASE A.Day WHEN 1 THEN CAST((E.Wages) AS VARCHAR)
ELSE ''N'' END + SPACE(3) +
CASE A.Night WHEN 1 THEN CAST((E.Wages/2) AS VARCHAR)
ELSE ''N'' END + SPACE(3) +
CASE A.FullNight WHEN 1 THEN CAST((E.Wages/2) AS VARCHAR) ELSE ''N'' END
),
E.Name As Employee, D.Name As Department,
SUM(
W.Wages
) OVER(PARTITION BY E.Name) As [Total for Month]
FROM dbo.EmpWages W
INNER JOIN dbo.Employee E ON
W.EmpID = E.ID
INNER JOIN dbo.Department D ON
E.DeptID = D.ID
JOIN dbo.Attendance A
ON W.EmpID = A.EmpID AND
W.FromDate = A.Date AND W.ToDate IS NULL
GROUP BY E.Name, D.Name, A.Day, A.Night, A.FullNight, A.Advance, FromDate, E.Wages, W.Wages, A.Advance
) as Header
PIVOT (Max(Days) FOR OYe IN(' + @ReportColumnNames + N')) As P1
ORDER BY 1
SELECT * FROM #temp_t
DROP TABLE #temp_t'
execute (@SQLtext);