sql server group by week,获取一周的第一天

时间:2014-06-24 06:34:48

标签: sql sql-server

我需要进行查询,以显示每个客户每周订购的每个项目/单位组合的数量(按周分组),同时显示每周的第一天。到目前为止,我有这个,但它没有显示每周星期一的日期

select o.customer_name, 
convert(varchar, DATEADD(wk, DATEDIFF(wk,0, min(o.delivery_date)), 0), 101) as first_day_of_week, 
item_code, 
(select i.[desc] from items i where i.item = oi.item_code) as description,
unit,
(SUM(oi.price) / SUM(oi.qty) ) as unit_price, 
SUM(oi.qty) as total_qty, 
SUM(oi.price) as total_charged 
from order_items oi inner join orders o on localID = local_order_id where o.[status] = 'submitted' and qty > 0
group by DATEPART(ww, delivery_date), customer_name, item_code, unit
order by customer_name, first_day_of_week, item_code

1 个答案:

答案 0 :(得分:0)

试试这个sql

select o.customer_name, 

dateadd(week, datediff(week, 0, o.delivery_date), 0) as first_day_of_week,
item_code, 
(select i.[desc] from items i where i.item = oi.item_code) as description,
unit,
(SUM(oi.price) / SUM(oi.qty) ) as unit_price, 
SUM(oi.qty) as total_qty, 
SUM(oi.price) as total_charged 
from order_items oi inner join orders o on localID = local_order_id where o.[status] = 'submitted' and qty > 0
group by dateadd(week, datediff(week, 0, o.delivery_date), 0), customer_name, item_code, unit

order by customer_name, first_day_of_week, item_code