SQL查询按周分配标准

时间:2015-01-28 19:14:25

标签: sql sql-server tsql

我必须按周编写数据库中站立支架数量的趋势报告。 我可以在下面的示例中获得按星期竖立的支架计数,并使用相同的查询进行拆解,但这不是我需要的。

SELECT COUNT(scaffID) Erected, WeekStart
FROM 
(
 SELECT ScaffID, 
        dateadd(week, datediff(day,0,Erected) / 7, 0) AS WeekStart  
 FROM Scaffolds
) o
GROUP BY WeekStart

我可以通过约会来获得我的站立支架,但我希望每个星期五的站立脚手架都说。

Declare @staticDate As DateTime
Set @staticDate = '2/1/2015'

Select COUNT(scaffID) As StandingScaffolds
from RequestInfo 
Where (    ErectDate<= @staticDate )
  And (    DismantleDate>= @staticDate
        or DismantleDate Is NULL
      )

这让我发疯,所以任何帮助都会非常感激。

菲尔

2 个答案:

答案 0 :(得分:0)

这应该给你一些开始......

DECLARE     
    @startDate date = '2015-01-01',
    @endDate date = '2015-01-28';

with myWeeks (myWeek) AS (
    select DATEPART(WEEK,@startDate) myWeek
    UNION ALL
    select myWeek + 1 from myWeeks
    where
        myWeek < DATEPART(WEEK,@endDate)
)
select 
    w,
    COUNT(s.Erected) standingScaffolds
from myWeeks w
left join Scaffolds s on
    w.myWeek between DATEPART(WEEK,s.Erected) and DATEPART(WEEK,s.Dismantled)

答案 1 :(得分:0)

您可能希望为此生成日期表(=每天有一行的表)。然后,您可以将其与此表连接,以便轻松地进行计算。

select d.date, count(s.scaffID)
from date d, scaffolds s
where s.erected <= d.date and
(dismantled>= d.date or dismantled is NULL) and
d.date >= @stardate and
d.date <= enddate
group by d.date

希望这没关系,现在无法测试。

日期表在其他情况下也很有用,例如你可以在那里度假。