SQL Query Group By Datetime problem?

后端 未结 2 958
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 20:55

I have this SQL query:

  SELECT DISTINCT 
         [BatchCode]
         ,SUM([Quantity]) as \'Created\'
         ,[TotalQuantity]
         ,[Status]
                 


        
相关标签:
2条回答
  • 2021-01-16 21:14

    Use CAST or CONVERT to alter the DATETIME format so the time portion is omitted:

      SELECT [BatchCode],
             SUM([Quantity]) as 'Created',
             [TotalQuantity],
             [Status],
             [Destination],
             CONVERT(VARCHAR(10), [DateCreated], 101) AS datecreated,
             [CreatedBy]
        FROM [FGIS].[dbo].[DropshipPackinglist]
    GROUP BY BatchCode, 
             TotalQuantity, 
             Status, 
             Destination, 
             CreatedBy, 
             ModifiedBy, 
             CONVERT(VARCHAR(10), [DateCreated], 101)
    
    0 讨论(0)
  • 2021-01-16 21:20

    I guess it's worth posting this separately:

    Using char conversions to chop the time off dates (cast or convert to varchar) is slower than using DateAdd(Day, DateDiff(Day, 0, DateCreated), 0). I worked up full script and performance testing results to support this assertion.

    SELECT DISTINCT 
       BatchCode
       ,SUM(Quantity) as Created
       ,TotalQuantity
       ,Status
       ,Destination
       ,DateAdd(Day, DateDiff(Day, 0, DateCreated), 0) as DayCreated
       ,CreatedBy
    FROM FGIS.dbo.DropshipPackinglist
    GROUP BY
       BatchCode,
       TotalQuantity,
       Status,
       Destination,
       CreatedBy,
       ModifiedBy,
       DateDiff(Day, 0, DateCreated) -- note that the DateAdd convert back to datetime is not needed
    

    Also, please note that your GROUP BY list is not the same as your SELECT list so some tweaking is needed.

    UPDATE

    It seems that the CPU savings for using DateAdd vs. varchar conversions, while a lot relatively, isn't a lot absolutely (just fractions of a millisecond per row). However, it is still a performance difference, and it seems best to me to save every bit possible.

    0 讨论(0)
提交回复
热议问题