sql server—sql查询,用于查找每周每一天为项目订购的每个类别中的单位

deikduxw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(320)

以下是我需要的细节:
查找过去7天内每周每一天已订购的每一类别的单位。-输出为:

Category | Sunday_units | Monday_units | Tuesday_units | Wednesday_units | Thursday_units | Friday_units | Saturday_units

查找每个客户在每个日期至少下两个订单的第二个最早订单id
我还想为这些表开发带有Map的er模型。为了开发一个具有基数的er模型,我认为:1个item-->可以有1个或多个order,1个order-->只能有一个item(根据schema),请验证模型基数是否合适。
我尝试使用case语句查找sqlserver查询。
架构:
订单

order_id varchar(20) composite primary key
customer_id numeric(35,0)
order_datetime timestamp
item_id varchar(10) composite primary key
order_quantity numeric(35,0)

订单样本摘录

order_id | customer_id | order_datetime | item_id | order_quantity
A-001    | 32483       | 2018-12-15 09:15:22 | B000 | 3                 
A-005    | 21456       | 2019-01-12 09:28:35 | B001 | 1
A-005    | 21456       | 2019-01-12 09:28:35 | B005 | 1
A-006    | 42491       | 2019-01-16 02:52:07 | B008 | 2

项目

item_id varchar(10) primary key
item_category varchar(18)

项目样本摘录

item_id | item_category
B000 | Outdoors
B001 | Outdoors
B002 | Outdoors
B003 | Kitchen
B004 | Kitchen

我创建的查询如下:
看看这个问题,我们怎么知道2019年10月1日会落在周四?我还想知道日期和相应的周计算。

Select i.item_category, 
    Sum(case when o.order_datetime = '01-10-2019' THEN o.Count(order_quantity) else null end) as Thursday_Units,
    Sum(case when o.order_datetime = '01-11-2019' THEN o.Count(order_quantity) else null end) as Friday_Units,
    Sum(case when o.order_datetime = '01-12-2019' THEN o.Count(order_quantity) else null end) as Saturday_Units,
    Sum(case when o.order_datetime = '01-13-2019' THEN o.Count(order_quantity) else null end) as Sunday_Units,
    Sum(case when o.order_datetime = '01-14-2019' THEN o.Count(order_quantity) else null end) as Monday_Units,
    Sum(case when o.order_datetime = '01-15-2019' THEN o.Count(order_quantity) else null end) as Tuesday_Units,
    Sum(case when o.order_datetime = '01-16-2019' THEN o.Count(order_quantity) else null end) as Wednesday_Units
from Orders o
inner join Items i on o.item_id = i.item_id
group by i.item_category
ff29svar

ff29svar1#

你可以用 datename() :

select 
    i.item_category, 
    sum(case when datename(weekday, o.order_datetime) = 'Sunday' then order_quantity end) as sunday_units,
    sum(case when datename(weekday, o.order_datetime) = 'Monday' then order_quantity end) as monday_units,
    ...
    sum(case when datename(weekday, o.order_datetime) = 'Saturday' then order_quantity end) as saturday_units,
from orders o 
inner join items i  on o.item_id = i.item_id
where o.order_datetime >= dateadd(day, -7, cast(getdate() as date))
group by i.item_category

我还添加了一个 where 在过去7天过滤的子句。请注意,使用此技术,列不表示连续的日期(如果今天是星期一,则上周五的数据比上周二的数据更新)。

相关问题