我当前正在使用以下代码从数据库中获取销售数据。它的问题在于,在没有销售的那些小时中,它不会显示0。我不介意对小时进行硬编码,但是我找不到找到这种方法的方法。因此,
1.st问题:我如何修改下面的代码以在0小时内没有销售的情况下显示0,
2.nd问题:如何从中获得有序列表。下面的代码会将9:00-10:00放置在列表的末尾,因为它不是两位数。
-- HOUR BASED SALES
select (CAST(DATEPART(HOUR, INSERTDATE) as varchar(255)) + ':00 -' +
CAST(DATEPART(HOUR, INSERTDATE) as varchar(255)) + ':59'
) as [time],
SUM (TOTAL) as REVENUE,
COUNT (RECEIPTID) AS TOTAL_SALES,
DEPOTID
From INVOICE INV
WHERE DEPOTID IN (25) AND TRANSDATE BETWEEN '20181025' AND '20181025'
Group By cast(datepart(hour, INSERTDATE) AS VARCHAR(255)), DEPOTID
ORDER BY CAST(DATEPART(HOUR, INSERTDATE) AS VARCHAR(255))
答案 0 :(得分:2)
您可以列出小时数并使用left join
:
select (cast(v.hh as varchar(255)) + ':00 -' +
cast(v.hh as varchar(255)) + ':59'
) as [time],
sum(TOTAL) as REVENUE,
sum(RECEIPTID) AS TOTAL_SALES,
depot
From (values (0), (1), . . . (23)
) v(hh) left join
invoice i
on datepart(hour, i.insertdate) = v.hh and
i.depotid in (25) and
i.transdate between '20181025' and '20181025'
group by v.hh, DEPOTID
order by v.hh