我有这个SQL查询:
SELECT DISTINCT
[BatchCode]
,SUM([Quantity]) as 'Created'
,[TotalQuantity]
,[Status]
,[Destination]
,[DateCreated]
,[CreatedBy]
FROM [FGIS].[dbo].[DropshipPackinglist]
GROUP BY BatchCode, TotalQuantity, Status, Destination, CreatedBy, ModifiedBy, DateCreated
结果如下:
BatchCode Created TotalQuantity Status Destination DateCreated CreatedBy
---------------------------------------------------------------------------------------------------------------
0005041007100AHWA11HG 86 86 CREATED MediTelecom S.A. 2010-09-10 00:00:00.000 NULL
0005041007100AHWA11HGK 19 50 ALLOCATED USA 2010-09-12 07:35:17.000 jy
0005041007100AHWA11HGK 31 50 ALLOCATED USA 2010-09-12 07:35:20.000 jy
我现在的问题是我不能分组DateCreated因为它有不同的时间。
我想仅按日期对其进行分组。示例:2010-09-12
感谢和问候......
答案 0 :(得分:4)
使用CAST or CONVERT更改DATETIME格式,以便省略时间部分:
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)
答案 1 :(得分:2)
我想这值得单独发布:
使用char转换来截断日期(转换或转换为varchar)比使用DateAdd(Day, DateDiff(Day, 0, DateCreated), 0)
要慢。我参与了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
另外,请注意您的GROUP BY列表与SELECT列表不同,因此需要进行一些调整。
<强>更新强>
似乎使用DateAdd与varchar转换的CPU节省虽然相对而言绝对不是很多(每行只有几分之一毫秒)。但是,它仍然是性能差异,我似乎最好保存每一点。