0

I have a table with the following structure in SQL Server 2005:

ID    Day     DayDate    TimeEntry  TimeOut   Rest     Monday
1   Monday   17-06-2013   08:00      18:00    14:30   17-06-2013
2   Tuesday  18-06-2013   08:00      18:00    14:30   17-06-2013

So on until week Monday field allows me to group all the days of a given week.

Now I need to gather the data in one record in a view:

Id DayDateMonday TimeEntryMonday TimeOutMonday RestMonday 
   DayDateTuesday TimeEntryTuesday TimeOutTuesday RestTuesday .... so on.

Any help?

4

1 回答 1

0

虽然在 SQL Server 2005 及更高版本中支持 PIVOT 子句,但在您的情况下手动旋转数据可能会更好,即借助分组和条件聚合。

但是,请注意:Id,如果它是ID原始表中的列,那么在您看来是没有意义的。每一天都有自己的 ID,并且您的视图连续几天聚集,因此在那里放置一个似乎没有任何意义ID。因此,出于此答案的目的,我将其替换为一周中的星期一日期(该Monday列重命名WeekDate为输出)。

除此之外,这是您的旧“手动”支点:

SELECT
  WeekDate = Monday,

  DayDateMonday   = MAX(CASE Day WHEN 'Monday' THEN DayDate   END),
  TimeEntryMonday = MAX(CASE Day WHEN 'Monday' THEN TimeEntry END),
  TimeOutMonday   = MAX(CASE Day WHEN 'Monday' THEN TimeOut   END),
  RestMonday      = MAX(CASE Day WHEN 'Monday' THEN Rest      END),

  DayDateTuesday   = MAX(CASE Day WHEN 'Tuesday' THEN DayDate   END),
  TimeEntryTuesday = ...  -- and so on

FROM timetable
GROUP BY
  Monday
;
于 2013-06-17T13:02:11.717 回答