sql从当天查找当月的工作日

时间:2015-02-01 18:58:44

标签: sql sql-server-2008

请帮我解决这个问题。使用SQL Server 2008 我需要查找当天的销售数量。 然后从当前日期找到工作日,并根据该工作日查找上个月所有特定工作日的销售平均值 例如:

select count(sales) from salestable where orderdate= getdate()

其中显示当前日期的销售计数 然后我需要找出在同一个工作日完成的销售的平均值,如果今天星期天找到该月所有星期日上个月销售的平均值。

3 个答案:

答案 0 :(得分:1)

我建议你借用数据仓库技术来创建一个Calendar表,你可以为你需要的范围内的每个日期预先填充1行。您可以基本上添加任何有用的列 - 在本例中为DayOfWeek和MonthID。然后你可以完全消除日期数学并使用连接 - 有点像这样(不完整但指向正确的方向):

select count(salestable.sales) as salescount, a.salesavg
from salestable 
join calendar on salestable.orderdate = calendar.calendardate
join (
  select monthid, dayofweek, avg(salestable.sales) as salesavg
  from salestable
  join calendar on salestable.orderdate = calendar.calendardate
  group by monthid, dayofweek) as a
on calendar.monthid = a.monthid and calendar.dayofweek = a.dayofweek
where calendar.calendardate = getdate()

您可以创建并填充日历表一次,并在每次需要执行日期操作时重复使用它。一旦你习惯了这种技术,你将永远不会回到数学日期。

答案 1 :(得分:0)

对于这种类型的查询Common Table Expressions非常有用。你可以使用DATEPART函数获取星期几。

答案 2 :(得分:0)

此解决方案也未经过测试,只是为了指出正确的方向。

此解决方案使用共同相关的子查询来获得平均销售额。

select 
    order_date, 
    count(sales) total_sales,
    (select avg(sales) 
        from sales_table 
        where order_date between dateadd(day,-30,@your_date) and @your_date
            and datepart(WEEKDAY,order_date) = datepart(WEEKDAY,@your_date)
     ) avg_sales_mth
from sales_table
where order_date = @your_date