SQL查询每小时细分销售额

时间:2015-05-24 13:34:55

标签: sql sql-server-2008

我有一个查询如下,它将返回今天的每个远程服务器销售 结果如下

datebooking NameOfDay   ORC CWP TC  TotalBooking    EmailSent   EmailNotSent
20150524    Sunday      447 144 272  1441           1441           0

日期预订实际上我已将其减少到8个数字

我的问题是,我可以按小时返回每个远程销售服务器故障吗?想象一下,有一天会有24行细节而不是每天一行 这意味着在预订日期我们将采用这种格式20150524上午12点到凌晨1点销售,凌晨2点到凌晨3点等等?我应该如何根据当前查询完成此查询?

SELECT 
    Convert(char(8), OrderH_dtmInitiated, 112)as datebooking,
      Datename (weekday, OrderH_dtmInitiated) As NameOfDay,
       --count(distinct OrderH_strCinemaId)as Cinemasite,   
       SUM(case when OrderH_strCinemaId like '1101' then 1 else 0 end)as ORC,
       SUM(case when OrderH_strCinemaId like '1102' then 1 else 0 end)as CWP,
       SUM(case when OrderH_strCinemaId like '1104' then 1 else 0 end)as TC,
       count(distinct OrderH_intID)as TotalBooking,  
       SUM(case when OrderH_strEmailConfirmationSent like 'Y' then 1 else 0 end) as EmailSent,
       SUM(case when OrderH_strEmailConfirmationSent is NULL then 1 else 0 end) as EmailNotSent   

    FROM [VISTAIT].[dbo].[tblOrderHistory]
    WHERE OrderH_dtmInitiated >= (SELECT     DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE() )))
    GROUP BY Convert(char(8), OrderH_dtmInitiated, 112), Datename (weekday, OrderH_dtmInitiated )
    ORDER by Convert(char(8), OrderH_dtmInitiated, 112) 

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您只需将小时添加到selectgroup by

SELECT Convert(char(8), OrderH_dtmInitiated, 112) as datebooking,
       datename(hour, OrderH_dtmInitiated) as hourbooking,
       . . .
FROM . . .
GRUOP BY Convert(char(8), OrderH_dtmInitiated, 112),
         datename(hour, OrderH_dtmInitiated)

这假设OrderH_dtmInitiated实际上有时间信息。

另一种方法是使用包含小时的日期/时间格式,因此很容易将其放入一个字段中:

SELECT Convert(char(13), OrderH_dtmInitiated, 121) as datebooking,
       . . .
FROM . . .
GROUP BY Convert(char(13), OrderH_dtmInitiated, 121)

格式将为" YYYY-MM-DD HH"。

编辑:

如果您想要一小时的上午/下午,可能最简单的方法是明确的case

SELECT Convert(char(8), OrderH_dtmInitiated, 112) as datebooking,
       (CASE WHEN datename(hour, OrderH_dtmInitiated) < '12'
             THEN datename(hour, OrderH_dtmInitiated) + ' AM'
             ELSE datename(hour, OrderH_dtmInitiated) + ' PM'
        END) as hourbooking,
       . . .
FROM . . .
GRUOP BY Convert(char(8), OrderH_dtmInitiated, 112),
         datename(hour, OrderH_dtmInitiated)

注意:我故意使用datename()编写逻辑。这样,整个case语句不需要在group by子句中。