TSql查询整个日期范围内的客户/订单摘要

时间:2019-05-31 16:13:51

标签: sql tsql

我有两个表:Customer表和Order表。客户表具有许多列,但需要的两列是Customer.Id和Customer.Name。同样,Order表也有许多列,再次只需要三列:Order.Id和Order.OrderDate,Order.CustomerId。我需要构建一个查询,该查询将按日期提供给定日期范围内的订单报告:DateStart到DateEnd。某些日子可能没有订单,而其他日子确实有订单,并非所有客户都会有订单,有些客户可能会有一个以上的订单。

这是预期的数据和报告。

Customer Table
Customer.Id     Customer.Name
1               One
2               Two
3               Three

Order Table
Order.Id        Order.CustomerId        Order.OrderDate
1               1                       2019-01-01
2               1                       2019-01-01
3               1                       2019-01-02
4               3                       2019-01-02
5               3                       2019-01-04

Results
Customer.Id     Customer.Name           Order.OrderDate Count
1               One                     2019-01-01      2
2               Two                     2019-01-01      0
3               Three                   2019-01-01      0
1               One                     2019-01-02      1
2               Two                     2019-01-02      0
3               Three                   2019-01-02      1
1               One                     2019-01-03      0
2               Two                     2019-01-03      0
3               Three                   2019-01-03      0
1               One                     2019-01-04      0
2               Two                     2019-01-04      0
3               Three                   2019-01-04      1

1 个答案:

答案 0 :(得分:1)

首先,您需要以某种方式创建一个包含所有日期的表(对于<form method="POST"> {% csrf_token %} <label for="Unidades">Selecione unidade</label> <select class="form-control" id="item_unidade"> {% for item_unidade in unidade2 %} <option>{{ item_unidade }}</option> {% endfor %} </select> <input type="submit"> ,没有订单)。然后,您可以交叉加入客户以创建所有组合并计算客户订单。

'2019-01-03'

理想情况下,应该有一个包含所有日期的表,而不是即时进行操作并根据declare @minDate date = (select min(OrderDate) from [Order]) declare @maxDate date = (select max(OrderDate) from [Order]) declare @Date date = @minDate create table #rangeOfDates (dat date) while @Date <= @maxDate begin insert into #rangeOfDates values (@Date) set @Date = dateadd(day , 1, @Date) end select c.Id ,c.Name ,r.dat as OrderDate ,count(o.Id) as [Count] from Customer as c cross join #rangeOfDates as r left join [Order] as o on c.Id = o.CustomerId and r.dat = o.OrderDate group by c.Id, c.Name, r.dat order by OrderDate, Id Id Name OrderDate Count 1 One 2019-01-01 2 2 Two 2019-01-01 0 3 Three 2019-01-01 0 1 One 2019-01-02 1 2 Two 2019-01-02 0 3 Three 2019-01-02 1 1 One 2019-01-03 0 2 Two 2019-01-03 0 3 Three 2019-01-03 0 1 One 2019-01-04 0 2 Two 2019-01-04 0 3 Three 2019-01-04 1 @minDate对其进行限制。