我部分在解决这个问题的方法上,但遇到了绊脚石,我认为可以通过枢轴来解决。
我有以下SQL查询,结合了两个临时表变量(可能会将这些变量更改为临时表,因为我认为性能可能会出现问题,因为它们会被大量击中):
SELECT MeterId, MeterDataOutput.BuildingId, MeterDataOutput.Value,
MeterDataOutput.TimeStamp, UtilityId, SnapshotId
FROM @MeterDataOutput as MeterDataOutput INNER JOIN @InsertOutput AS InsertOutput
ON MeterDataOutput.BuildingId = InsertOutput.BuildingId
AND MeterDataOutput.[Timestamp] = InsertOutput.[TimeStamp]
这会产生下表:
然后我通过BuildingId,SnapshotId,Timestamp,Utility将查询修改为分组,并应用SUM()函数来聚合Value字段(并将MeterId删除为不需要的),如下所示:
SELECT MeterDataOutput.BuildingId, SUM(MeterDataOutput.Value) AS Value, MeterDataOutput.TimeStamp, UtilityId, SnapshotId
FROM @MeterDataOutput as MeterDataOutput
INNER JOIN @InsertOutput AS InsertOutput
ON MeterDataOutput.BuildingId = InsertOutput.BuildingId
AND MeterDataOutput.[Timestamp] = InsertOutput.[TimeStamp]
GROUP BY MeterDataOutput.BuildingId, MeterDataOutput.TimeStamp, UtilityId, SnapshotId
此查询为我提供了下表:
现在我遇到的麻烦是将UtilityId值转换为列,并将值字段中的值放在每列下面。即:
对于参考buildingId,时间戳,快照和值是可变的。 UtilityId值6总是'Electricity',7总是'Gas',8总是'Water'。
我实际上已经开始获得SQL lark的手了:)
答案 0 :(得分:1)
也许是这样的:
SELECT
pvt.BuildingId,
pvt.SnapshotId,
pvt.TimeStamp,
pvt.[6] AS Electricity,
pvt.[7] AS Gas,
pvt.[8] AS Water
FROM
(
SELECT
MeterDataOutput.BuildingId,
MeterDataOutput.Value,
MeterDataOutput.TimeStamp,
UtilityId,
SnapshotId
FROM @MeterDataOutput as MeterDataOutput
INNER JOIN @InsertOutput AS InsertOutput
ON MeterDataOutput.BuildingId = InsertOutput.BuildingId
AND MeterDataOutput.[Timestamp] = InsertOutput.[TimeStamp]
) AS SourceTable
PIVOT
(
SUM(Value)
FOR UtilityId IN ([6],[7],[8])
) AS pvt