SQL 服务器 - 将天转换为列,将小时转换为行
SQL Server - Convert Days as Column, Hour as row
我正在寻找一种方法来转换行以将日期时间数据的日期显示为列,将小时显示为一个月中的第一行。
这是我一个月的示例数据:
Time | Value
--------------------------------
2016-10-01 00:00:00 | 23
2016-10-01 00:30:00 | 35
..... | .....
2016-10-31 23:30:00 | 52
我想要的结果是
Time | 1 | .... | 31 | <-- Day 1 - 31
---------------------------------------
00:00:00 | 23 | .... | .... |
00:30:00 | 35 | .... | .... |
... | .... | .... | .... |
23:30:00 | .... | .... | 52 |
我如何构建结果?
您可以使用 Conditional Aggregate
来做到这一点
select cast([Time] as time),
Max(case when DAY([Time]) = 1 then Value end) As [1]
Max(case when DAY([Time]) = 2 then Value end) As [2]
Max(case when DAY([Time]) = 3 then Value end) As [3]
.....
Max(case when DAY([Time]) = 31 then Value end) As [31]
From yourtable
Where Month([Time]) = 10 -- pass the required month
Group by cast([Time] as time)
我正在寻找一种方法来转换行以将日期时间数据的日期显示为列,将小时显示为一个月中的第一行。 这是我一个月的示例数据:
Time | Value
--------------------------------
2016-10-01 00:00:00 | 23
2016-10-01 00:30:00 | 35
..... | .....
2016-10-31 23:30:00 | 52
我想要的结果是
Time | 1 | .... | 31 | <-- Day 1 - 31
---------------------------------------
00:00:00 | 23 | .... | .... |
00:30:00 | 35 | .... | .... |
... | .... | .... | .... |
23:30:00 | .... | .... | 52 |
我如何构建结果?
您可以使用 Conditional Aggregate
来做到这一点
select cast([Time] as time),
Max(case when DAY([Time]) = 1 then Value end) As [1]
Max(case when DAY([Time]) = 2 then Value end) As [2]
Max(case when DAY([Time]) = 3 then Value end) As [3]
.....
Max(case when DAY([Time]) = 31 then Value end) As [31]
From yourtable
Where Month([Time]) = 10 -- pass the required month
Group by cast([Time] as time)