我的場景比OP示例稍微複雜一點,所以我以爲我會分享來幫助其他有類似問題的人。我需要按日期對銷售訂單進行分組,而訂單則使用日期時間進行存儲。
因此,在「天」查詢表中,我無法真正將日期時間存儲爲'00:00:00.000'並獲得任何匹配。因此我以字符串形式存儲,並試圖直接加入轉換後的值。
這沒有返回任何零行,解決方案是做一個子查詢返回已經轉換爲一個字符串的日期。
示例代碼如下:
declare @startDate datetime = convert(datetime,'09/02/2016')
declare @curDate datetime = @startDate
declare @endDate datetime = convert(datetime,'09/09/2016')
declare @dtFormat int = 102;
DECLARE @null_Date varchar(24) = '1970-01-01 00:00:00.000'
/* Initialize #days table */
select CONVERT(VARCHAR(24),@curDate, @dtFormat) as [Period] into #days
/* Populate dates into #days table */
while (@curDate < @endDate)
begin
set @curDate = dateadd(d, 1, @curDate)
insert into #days values (CONVERT(VARCHAR(24),@curDate, @dtFormat))
end
/* Outer aggregation query to group by order numbers */
select [Period], count(c)-case when sum(c)=0 then 1 else 0 end as [Orders],
sum(c) as [Lines] from
(
/* Inner aggregation query to sum by order lines */
select
[Period], sol.t_orno, count(*)-1 as c
from (
/* Inner query against source table with date converted */
select convert(varchar(24),t_dldt, @dtFormat) as [shipdt], t_orno
from salesorderlines where t_dldt > @startDate
) sol
right join #days on shipdt = #days.[Period]
group by [Period], sol.t_orno
) as t
group by Period
order by Period desc
drop table #days
樣品結果:
Period Orders Lines
2016.09.09 388 422
2016.09.08 169 229
2016.09.07 1 1
2016.09.06 0 0
2016.09.05 0 0
2016.09.04 165 241
2016.09.03 0 0
2016.09.02 0 0
提示:數字(又名日)表 – 2011-05-05 15:02:42