SQL Server 2008 列转行 实例
原始表中的数据如下所示:
需求得到如下结果:
SQL如下:
SELECT prodline, week, weekday, weekdaysip, Dateadd(dd, CONVERT(INT, RIGHT(week, 2)) * 7 - Datepart(dw, Cast(CONVERT( INT, LEFT(week, 4) ) - 1 AS VARCHAR(4)) + '-12-31') + CASE weekday WHEN 'Mon' THEN 1 WHEN 'Tu' THEN 2 WHEN 'Wed' THEN 3 WHEN 'Thu' THEN 4 WHEN 'Fri' THEN 5 ELSE 0 END, Cast(CONVERT(INT, LEFT(week, 4)) AS VARCHAR(4)) + '-01-01') AS WeekdayDate FROM apps.target_sip UNPIVOT(weekdaysip FOR weekday IN (mon, tu, wed, thu, fri)) P