0

在我的应用程序中,我只想得到number of sales in a day by diiferent time interval

-----------------------------------------------------
Interval                     |  Count
-----------------------------------------------------
00:30 to 0:130               |  3
01:30 to 10:30               |  4
02:30 to 03:30               |  5
.. 
..
12:30 to 00:30               |  10
----------------------------------------------------- 

我尝试了如下查询

select '00:30 to 01:30' as intrval , COUNT(*) AS 'count' from Pharmacy.tblSalesHdr  SH
where CAST(SH.created_Date AS TIME)  BETWEEN '00:30' AND '00:30'

UNION ALL

select '01:30 to 02:30' as intrval , COUNT(*) AS 'count' from Pharmacy.tblSalesHdr  SH
where CAST(SH.created_Date AS TIME)  BETWEEN '01:30' AND '02:30'

UNION ALL

select '02:30 to 03:30' as intrval , COUNT(*) AS 'count' from Pharmacy.tblSalesHdr  SH
where CAST(SH.created_Date AS TIME)  BETWEEN '02:30' AND '03:30'

and so on...

我只是想知道是否有任何better and optimized method实现这一目标。如果有人知道请分享。

4

1 回答 1

3

你可以这样做:创建一个临时表,定义你想要的时间间隔,然后将它加入到你的销售表中。您甚至可以为该任务创建一个永久表。

  CREATE TABLE #Intervals (INTERVAL VARCHAR(20), FromTime TIME, ToTime TIME)
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('00:30 to 01:30', '00:30:00', '01:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('01:30 to 02:30', '01:30:00', '02:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('02:30 to 03:30', '02:30:00', '03:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('03:30 to 04:30', '03:30:00', '04:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('04:30 to 05:30', '04:30:00', '05:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('05:30 to 06:30', '05:30:00', '06:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('06:30 to 07:30', '06:30:00', '07:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('07:30 to 08:30', '07:30:00', '08:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('08:30 to 09:30', '08:30:00', '09:30:00')
  INSERT INTO #Intervals (INTERVAL, FromTime, ToTime) VALUES  ('09:30 to 10:30', '09:30:00', '10:30:00')
  -- etc...

  SELECT I.Interval, SUM(case when SH.created_Date IS NULL THEN 0 ELSE 1 END) 
  FROM #Intervals I
  LEFT JOIN Pharmacy.tblSalesHdr SH 
      ON CAST(SH.created_Date AS TIME) >= I.FromTime 
      AND CAST(SH.created_Date AS TIME) < I.ToTime
  GROUP BY I.Interval

  DROP TABLE #Intervals
于 2012-11-21T07:06:42.503 回答