T-SQL查询,总结销售日志表中的每小时销售数量

时间:2015-02-02 13:22:55

标签: sql-server tsql

我有一张销售表,而不是捕获物品的销售额。 (简化)Sales表包含以下列:

[InsertedDateTime] [datetime] NOT NULL,
[ItemCode] [bigint] NOT NULL,
[Qty] [float] NULL

我需要一个T-SQL查询,它根据InsertedDateTime返回每天每小时内每个ItemCode的总数量:

,,,

我可以只使用一个查询来执行此操作,还是需要先将数据处理到“摘要”表中?

3 个答案:

答案 0 :(得分:1)

使用Group bySum

SELECT [ItemCode],
       [InsertedDateTime],
       Datepart(hour, [InsertedDateTime]) [Hour],
       Sum(qty) Hourly_Total
FROM   yourtable
GROUP  BY [ItemCode],
          [InsertedDateTime],
          Datepart(hour, [InsertedDateTime]) 

答案 1 :(得分:0)

使用CTE获取每小时的详细信息。

;With CTE AS
(
SELECT 1 AS Cnt
UNION ALL
SELECT Cnt + 1 FROm CTE WHERE cnt + 1 <= 24
)

SELECT A.cnt AS [Hour], B.[ItemCode],
       B.[InsertedDateTime],
       B.Hourly_Total FROM CTE AS A
Left join
(
SELECT [ItemCode],
       [InsertedDateTime],
       Datepart(hour, [InsertedDateTime]) AS [hour],
       Sum(qty) Hourly_Total
FROM   yourtable
GROUP  BY [ItemCode],
          [InsertedDateTime],
          Datepart(hour, [InsertedDateTime]) 

) AS B
ON A.Cnt = [B.hour]

答案 2 :(得分:0)

CREATE TABLE [dbo].[Sales](
[InsertedDateTime] [datetime] NOT NULL,
[ItemCode] [bigint] NOT NULL,
[Qty] [float] NULL

此存储过程传递一个字符串,就像日期'2014-2-2'

一样
CREATE PROCEDURE [dbo].[GetQuanitySoldByHours]
 (
      @Date datetime
 )

AS 

BEGIN
Create Table #DayHours  -- A Primary Table just To make the left join
(
   hour bigint
)

Declare @Counter int = 0;

WHILE @Counter <= 23    -- Adding values to temp table in loop
BEGIN    
    INSERT INTO #DayHours VALUES (@Counter)
    SET @Counter = @Counter + 1;
END



SELECT
    @Date AS DAYDATE
    dh.hour AS DAYHOUR ,
    ISNULL(s.ItemCode,0) AS ITEMCODE,
    ISNULL(SUM(s.Qty),0) AS SOLDQUATITY 
FROM #DayHours dH 
left outer join 
dbo.Sales s 
ON dh.hour = DATEPART(hh,s.InsertedDateTime) 
GROUP BY s.ItemCode, dh.hour

DROP TABLE #DayHours   -- Droping temp table 

END