可以做到,但您不会轻易获得动态查询。
正如对您问题的评论所暗示的那样,使用您实际执行 SQL 的编程语言可能更容易完成。
如果您事先知道所有“类别”(在您的情况下为日期列),则可以创建如下 SQL:
select
sensorid,
max(case when date = 0 then value else 0 end) as date0,
max(case when date = 1 then value else 1 end) as date1,
max(case when date = 2 then value else 2 end) as date2,
max(case when date = 3 then value else 3 end) as date3,
max(case when date = 4 then value else 4 end) as date4
from
yourtable
group by
sensorid
这是您可以试验的完整LINQPad脚本:
USE master
GO
IF EXISTS (SELECT * FROM sysdatabases WHERE name = 'SO16639641')
DROP DATABASE SO16639641
GO
CREATE DATABASE SO16639641
GO
USE SO16639641
GO
CREATE TABLE original
(
sensorid int,
date_ int,
value int
)
GO
INSERT INTO original
VALUES
(65000, 00, 32),
(65000, 01, 40),
(65000, 02, 35),
(65000, 03, 37),
(65000, 04, 39),
(65001, 00, 06),
(65001, 01, 10),
(65001, 02, 15),
(65001, 03, 26),
(65001, 04, 39)
GO
SELECT
sensorid,
MAX(CASE WHEN date_ = 0 THEN value ELSE 0 END) AS date0,
MAX(CASE WHEN date_ = 1 THEN value ELSE 1 END) AS date1,
MAX(CASE WHEN date_ = 2 THEN value ELSE 2 END) AS date2,
MAX(CASE WHEN date_ = 3 THEN value ELSE 3 END) AS date3,
MAX(CASE WHEN date_ = 4 THEN value ELSE 4 END) AS date4
FROM
original
GROUP BY
sensorid
GO
或者在这里下载。
我还添加了一个动态版本,它会根据数据确定要添加哪些日期列。涉及更多一点,但您可以在上面的链接中找到这两个脚本。