SQL Cross-Tabulation,Pivot

时间:2016-03-22 12:13:05

标签: asp.net sql-server pivot

我在一家需要改进班次管理概述的公司工作。他们已经习惯了excel表,我的意思是在Web浏览器上实现解决方案。表格的格式如下:

                 Employee1    Employee2    Employee3
DD/MM/YYY1 Mon   Shift1       Shift2       Shift3
DD/MM/YYY2 Tue   Shift2       Shift3       Shift1
DD/MM/YYY3 Wed   Shift3       Shift1       Shift2
DD/MM/YYY4 Thu   Shift1       Shift2       Shift3
DD/MM/YYY5 Fri   Shift2       Shift3       Shift1

我的问题是,现在看起来像这样:

Date           Shift_Type_Name   Employee_Name
DD/MM/YYY1 Mon Shift1            Employee1
DD/MM/YYY1 Mon Shift2            Employee2
DD/MM/YYY1 Mon Shift3            Employee3 

我使用 ASP.net 4.6.1 Microsoft SQL Server

我会为感兴趣的人附上数据库设计的照片。

Microsoft SQL Database Photo

我应该专注于SQL查询为每位员工动态添加列,还是使用ListView模板在此设计中显示?等等?

感谢您的关注和帮助。我从这个社区中受益匪浅。 :)

修改 我最接近问题的解决方案(也许这会帮助你更好地理解我的问题)是这个伪代码:

SELECT
[Date].[date] AS 'Date',
FOR EACH( SELECT [Employee].* AS THIS ){
    SELECT [Shift_Type].[name] AS [THIS].[Name] + ' Morning',
        WHERE [Shifts].[Type] = @morning_hours AND [Shifts].[Employee_fk] = [THIS].[ID]
    SELECT [Shift_Type].[name] AS [THIS].[Name] + ' Evening',
        WHERE [Shifts].[Type] = @evening_hours AND [Shifts].[Employee_fk] = [THIS].[ID]
    }
FROM [Groups]
JOIN [Employee]
    ON [Groups].[id] = [Employee].[group_fk]
JOIN [Shifts]
    ON [Employee].[id] = [Shifts].[employee_fk]
JOIN [Shift_Types]
    ON [Shift_Types].[id] = [Shifts].[type_fk]
RIGHT JOIN [Date]
    ON [Date].[id] = [Shifts].[date_fk]
JOIN [Public_Holidays]
    ON [Public_Holidays].[date_fk] = [Date].[id]

我知道FOR EACH不是SQL服务器中的一个选项,但希望这能描述我想要实现的目标。

1 个答案:

答案 0 :(得分:0)

在做了一些额外的研究后,我发现this video对解释旋转非常有帮助。

以下是我在其帮助下所做的查询:

DECLARE @ColumnNames NVARCHAR(MAX) = '';
DECLARE @SQuery NVARCHAR(MAX) = '';

SELECT @ColumnNames += QUOTENAME(Employee.name) + ','
FROM Employee;

SET @ColumnNames =LEFT(@ColumnNames, LEN(@ColumnNames) - 1);


SET @SQuery =
'
SELECT * FROM
    (SELECT
    Employee.name as Name,
    Date.date as ''Date'',
    Shift_Types.name as ''Shift''
FROM [Groups]
    JOIN [Employee]
        ON [Groups].[id] = [Employee].[group_fk]
    JOIN [Shifts]
        ON [Employee].[id] = [Shifts].[employee_fk]
    JOIN [Shift_Types]
        ON [Shift_Types].[id] = [Shifts].[type_fk]
    RIGHT JOIN [Date]
        ON [Date].[id] = [Shifts].[date_fk]
    JOIN [Public_Holidays]
        ON [Public_Holidays].[date_fk] = [Date].[id]) as BaseData
PIVOT(
    MIN(BaseData.[Shift])
    FOR BaseData.[Name]
    IN (' + @ColumnNames + ')
) as PivotTable'

EXEC(@SQuery);

我希望这有助于某人。 :)