I want to apply unpivot function in SQL Server

bvjveswy  于 2023-04-28  发布在  SQL Server
关注(0)|答案(1)|浏览(172)

I have below table
| Monday | Tuesday | Wednesday | Thursday | Friday | WeekStartsOn |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 8 | 8 | 8 | 8 | 8 | 2019-09-06 |

I want to convert it to below table

DayOftheWeekActualHrsWeekStartsOnTimecardDate
Monday82019-09-062019-09-07
Tuesday82019-09-062019-09-08
Wednesday82019-09-062019-09-09
Thursday82019-09-062019-09-10
Friday82019-09-062019-09-11

The logic To add **TimecardDate **is for Monday-->WeekstartsOn+1, Tuesday--> WeekStartsOn+2 .... , Friday--> WeekstartsOn+5

I have tried below Query

SELECT ActualHrs,DayOftheWeek,WeekStartsOn
FROM (select Monday,Tuesday,Wednesday,Thursday,Friday,WeekStartsOn
from itplanning.enriched.timecard_enriched_current) as cp 
UNPIVOT 
( 
ActualHrs FOR DayOftheWeek IN (Monday,Tuesday,Wednesday,Thursday,Friday ) 
) 
AS PivotTable
where ActualHrs<>0

with this Above query, I have got below table

DayOftheWeekActualHrsWeekStartsOn
Monday82019-09-06
Tuesday82019-09-06
Wednesday82019-09-06
Thursday82019-09-06
Friday82019-09-06

I am unable to do the TimecardDate column.

Actual table is below
| Monday | Tuesday | Wednesday | Thursday | Friday | WeekStartsOn |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 8 | 8 | 8 | 8 | 8 | 2019-09-06 |

Expected Table is below

DayOftheWeekActualHrsWeekStartsOnTimecardDate
Monday82019-09-062019-09-07
Tuesday82019-09-062019-09-08
Wednesday82019-09-062019-09-09
Thursday82019-09-062019-09-10
Friday82019-09-062019-09-11
wfsdck30

wfsdck301#

You can do something like this instead:

SELECT  v.d,v.hours,DATEADD(DAY, v.addDay, WeekStartsOn), WeekStartsOn
FROM itplanning.enriched.timecard_enriched_current
CROSS APPLY (
  VALUES(Monday,'Monday', 1),(Tuesday,'Tuesday', 2),(Wednesday, 'Wednesday', 3),(Thursday, 'Thursday', 4),(Friday, 'Friday', 5)
 ) v(hours, d, addDay)
where hours<>0

I unpivot manually and creates a two column table containing week and how many days to add to start of the week

相关问题