我有一个包含四行的表:id(主键,自动增量),值,类型和时间。
id value type time
1 1.2 1 2017-10-26 16:16:49.350
2 12.4 2 2017-10-26 16:16:49.350
3 0.6 3 2017-10-26 16:16:49.350
4 1.1 4 2017-10-26 16:16:49.350
5 1.8 1 2017-10-25 14:12:24.650
6 3.2 2 2017-10-25 14:12:24.650
7 0.2 3 2017-10-25 14:12:24.650
8 1.2 4 2017-10-25 14:12:24.650
是否可以根据类型和时间(通过查询或存储过程)将这些行转换为列?像这样的东西:
(type)1 2 3 4 time
1.2 12.4 0.6 1.1 2017-10-26 16:16:49.350
1.8 3.2 0.2 1.2 2017-10-25 14:12:24.650
PS:每四种类型共享相同的时间。
答案 0 :(得分:2)
试试这个:
DECLARE @DataSource TABLE
(
[id] SMALLINT
,[value] DECIMAL(9,1)
,[type] TINYINT
,[time] DATETIME2
);
INSERT INTO @DataSource ([id], [value], [type], [time])
VALUES (1, 1.2, 1, '2017-10-26 16:16:49.350')
,(2, 12.4, 2, '2017-10-26 16:16:49.350')
,(3, 0.6, 3, '2017-10-26 16:16:49.350')
,(4, 1.1, 4, '2017-10-26 16:16:49.350')
,(5, 1.8, 1, '2017-10-25 14:12:24.650')
,(6, 3.2, 2, '2017-10-25 14:12:24.650')
,(7, 0.2, 3, '2017-10-25 14:12:24.650')
,(8, 1.2, 4, '2017-10-25 14:12:24.650');
SELECT [1], [2], [3], [4], [time]
FROM
(
SELECT [value], [type], [time]
FROM @DataSource
) DS
PIVOT
(
MAX([value]) FOR [type] IN ([1], [2], [3], [4])
) PVT
ORDER BY [time] DESC;
答案 1 :(得分:2)
以下是使用条件聚合或交叉表的另一种选择。
select Type1 = max(case when type = 1 then value)
Type2 = max(case when type = 2 then value)
Type3 = max(case when type = 3 then value)
Type4 = max(case when type = 4 then value)
, time
from YourTable
group by time
答案 2 :(得分:0)
你可以使用PIVOT:
SELECT
[1] type1
, [2] type2
, [3] type3
, [4] type4
, time
FROM
(
SELECT
value
, type
, time
FROM table
) T
PIVOT
(
SUM (value)
FOR type IN
(
[1], [2], [3], [4]
)
) P