我的表格中有DateTime,
类型的列我想在日期时间列上进行操作,以便日期显示为列(星期一,星期二等星期几)。
所以例如我有一个这样的表(不记得SQL Server如何显示完整的日期时间,但你明白了):
BugNo | DateOpened | TimeSpent
1234 | 16/08/2010 | 1.0
4321 | 16/08/2010 | 3.5
9876 | 17/08/2010 | 1.5
6789 | 18/08/2010 | 7.0
6789 | 19/08/2010 | 6.5
6789 | 20/08/2010 | 2.5
我想转向DateOpened
列以创建像这样的结果集
|TimeSpentOnBugByDay| Mon | Tue | Wed | Thu | Fri | Sat | Sun
1234 1
4321 3.5
9876 1.5
6789 7.0
6789 6.5
6789 2.5
我应该指出,我一次只会检索一周。
我不确定这是否可行,但我很确定我之前见过这样的事情(我没写过)。
答案 0 :(得分:4)
你可以这样做
SELECT BugNo, [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday]
FROM (
SELECT BugNo, DATENAME(dw, DateOpened) AS DayWeek, TimeSpent
FROM Bugs
) AS src
pivot (
SUM(TimeSpent) FOR DayWeek IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])
) AS pvt