2015-09-08 144 views
0

我有這樣的表格;按日期的SQL數據透視表

enter image description here

我要顯示我的數據是這樣;

PersonelName------EnterDate1------EnterDate2------EnterDate3------EnterDateN 
    Michael------------6---------------8----------------7----------TotalWorkHour 
    Jason--------------5---------------8----------------6----------TotalWorkHour 
    Terra--------------6---------------6----------------6----------TotalWorkHour 
    Amelie-------------8---------------8----------------7----------TotalWorkHour 

EnterDates必須是動態的,兩天之間。 我有一張人事表。

我不能形象化這個邏輯。我不能理解樞軸。請幫幫我。 謝謝你。

+0

你想要返回一個動態的列數嗎?這是無法完成的,SELECT總是返回特定數量的列,與任何數據無關。 – jarlh

+0

我有一個c#項目,我可以處理日期或列名 – MehmetF

+0

如果您在某種類型的C#解決方案中呈現數據,我會嘗試在代碼中執行pivoting,而不是在sql中。 – larsts

回答

-1

如果你想要做一個動態的支點,你必須使用動態SQL

假設你想通過日期,而不是日期/時間轉動時,SQL看起來像: -

create procedure dbo.[Personnel_Pivot](@fromDate date,@toDate date) 
as 
begin 
    SET NOCOUNT ON; 
    DECLARE @LoopDate date,@MaxDate date,@InSQL VARCHAR(max),@InSQL2 VARCHAR(max),@BigSql VARCHAR(max) 
    SELECT @MaxDate = max(enterdate),@LoopDate = min(enterdate) from [dbo].[PersonnelLog] where cast(enterdate as date) between @fromDate and @toDate 
    WHILE @LoopDate <= @MaxDate 
    BEGIN 
     SET @InSQL = COALESCE(@InSQL + ',','') + '[' + convert(varchar(10),@Loopdate,103) + ']' 
     SET @InSQL2 = COALESCE(@InSQL2 + ',','') + '[' + convert(varchar(10),@Loopdate,103)+ ']' 
     --print @i 
     set @LoopDate= (select distinct MIN(enterdate) from [dbo].[PersonnelLog] where EnterDate>@Loopdate and cast(enterdate as date) between @fromDate and @toDate) 
    END 
    --print @InSQL2 
    set @BigSql= 
    ' 
    select PersonnelID,'[email protected]+' 
    from 
     (
     select convert(varchar(10),cast(enterdate as date),103) as EnterDate,PersonnelID 
     from [dbo].[PersonnelLog] 
     ) p 
    PIVOT 
     (
     count(EnterDate) 
     for EnterDate in ('[email protected]+') 
     ) as p2 
    ' 
    --print @BigSQL 
    EXECUTE (@BigSQL) 
end 

希望你應該能夠從那裏得到它