0

I have a table called AllData. This table has a column called UTCTimethat which has time in every 15 mins, the time start and end time are the following:

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

Another column is called Values

31.2775
37.2275
37.595
35.0975

The problem is: I want to check if there is a NULL or 0 value in an hourly time span! Basically, I want a query that display a new column that is 1 hour time and next to it two columns NoData, Zero Data Just like this

1 hourTime                                         NoData  ZeroData

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

NoData and ZeroData values are 0 because based on the Values column I don't have Null or 0 Data. Any help is appreciated.

4

1 回答 1

0

There are probably better ways to do this but here's one way:

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'
于 2013-06-26T20:37:38.700 回答