GROUP BY 、 HAVING 、および ORDER BY 句を使用した単純なSQLクエリがあります。HAVING 句には、 GROUP BY で使用したくないフィールドがいくつかありますが、可能ですか? データを毎時グループ化する必要があり、 HAVING に日付フィールドがあるため、グループ化が適切に機能しません。コードは次のとおりです。
alter procedure [dbo].[sp_metadata_inflow]
@grp_name varchar(40) , @subgrp_name varchar(40)
as
begin
declare @i as int , @j as int,@k as int,@d as datetime , @m as datetime,@y as datetime;
set @d = datepart(day,'2012-12-13 10:54:55.000');
set @m = datepart(month,'2012-12-13 10:54:55.000');
set @y = datepart(YEAR,'2012-12-13 10:54:55.000');
set @i = 1;
set @j = @i - 1;
while (@i <=24)
begin
(SELECT top 5 @i,
ContactReason,
@grp_name,
@subgrp_name,
COUNT(*)
FROM [ISRM].[dbo].[ITSM01ISRM]
GROUP BY ContactReason,datepart(day,CreatedDate),CurrentGroup,CurrentSubGroup
HAVING (
datepart(day,CreatedDate)= @d AND datepart(MONTH,CreatedDate)= @m
AND datepart(year,CreatedDate) = @y AND datepart(hour,CreatedDate) <= @i
AND datepart(hour,CreatedDate) >=@j
)
AND (CurrentGroup = @grp_name) AND (CurrentSubGroup = @subgrp_name)
);
set @i = @i + 1;
set @j = @i -1;
end
end
go