下面是我需要的详细信息:
Category | Sunday_units | Monday_units | Tuesday_units | Wednesday_units | Thursday_units | Friday_units | Saturday_units
为每位客户至少下达两个订单的日期查找第二个最早的ORDER_ID
我也想用这些表的映射来开发ER模型。为了开发具有基数的ER模型,我认为:1个项目->可以有1个或多个订单1个订单--->只能有一个物料(根据架构)请验证模型基数是否正确。
我尝试使用case语句查找SQL Server查询。
模式:
ORDERS
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)
从ORDERS中提取的样本
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
ITEMS
item_id varchar(10) primary key
item_category varchar(18)
从ITEMS中提取的样本
item_id | item_category
B000 | Outdoors
B001 | Outdoors
B002 | Outdoors
B003 | Kitchen
B004 | Kitchen
我创建的查询如下:
查看查询,我们如何知道2019年10月10日是星期四?我还想知道日期和相应的星期计算。
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
您可以使用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