SQL编程将4行合并为1并添加3列

时间:2013-06-26 18:32:24

标签: sql

我有一个名为AllData的表。该表有一个名为UTCTimethat的列,每隔15分钟有一个时间,时间开始和结束时间如下:

DECLARE @StartTime datetime,
        @EndTime datetime,
        @Timeframe int,
        @ByHour bit = 1;

SET @Timeframe = CAST(700 * RAND() AS int);
SET @Timeframe = CASE WHEN @Timeframe = 0 THEN 1 ELSE @Timeframe END

SET @StartTime = dateadd(hh, -1 * @Timeframe, CAST(CONVERT(varchar(14), getutcdate(), 121) + '00' AS datetime));
SET @EndTime = dateadd(hh, @Timeframe, @StartTime);

UTCTimethat

2013-06-24 23:00:00.000
2013-06-24 23:15:00.000
2013-06-24 23:30:00.000
2013-06-24 23:45:00.000

另一列称为值

31.2775
37.2275
37.595
35.0975

问题是:我想检查每小时时间跨度内是否有NULL或0值!基本上,我想要一个显示1小时时间的新列的查询,并且旁边有两列NoData,Zero Data 就像这样

1 hourTime                                         NoData  ZeroData

2013-06-24 23:00:00.000 - 2013-06-24 23:45:00.000  0       0

NoData和ZeroData值为0,因为根据Values列,我没有Null或0 Data。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

可能有更好的方法可以做到这一点,但这是一种方式:

select cast(datepart(yyyy, UTCTimethat) as varchar(4)) + '-' +
   cast(datepart(mm, UTCTimethat) as varchar(2)) + '-' +
   cast(datepart(dd, UTCTimethat) as varchar(2)) + ' ' +
   cast(datepart(hh, UTCTimethat) as varchar(2)) + ':00:000 - ' +
   cast(datepart(yyyy, UTCTimethat) as varchar(4)) + '-' +
   cast(datepart(mm, UTCTimethat) as varchar(2)) + '-' +
   cast(datepart(dd, UTCTimethat) as varchar(2)) + ' ' +
   cast(datepart(hh, UTCTimethat) as varchar(2)) + ':45:000' as HourTime,
   sum(case when Values is null then 1 else 0 end) as NoData,
   sum(case when Values = 0 then 1 else 0 end) as ZeroData
from AllData
where isnull(Values, 0) = 0
group by cast(datepart(yyyy, UTCTimethat) as varchar(4)) + '-' +
   cast(datepart(mm, UTCTimethat) as varchar(2)) + '-' +
   cast(datepart(dd, UTCTimethat) as varchar(2)) + ' ' +
   cast(datepart(hh, UTCTimethat) as varchar(2)) + ':00:000 - ' +
   cast(datepart(yyyy, UTCTimethat) as varchar(4)) + '-' +
   cast(datepart(mm, UTCTimethat) as varchar(2)) + '-' +
   cast(datepart(dd, UTCTimethat) as varchar(2)) + ' ' +
   cast(datepart(hh, UTCTimethat) as varchar(2)) + ':45:000'