Sql循环 - 除此之外

时间:2015-06-01 13:54:20

标签: sql sql-server-2008

我已经在SQL语句中及其周围阅读了关于循环(优点和缺点)的线程。我需要"循环"通过12小时,小时,小时,并想知道是否有比#34; Do-While-Loop等更好的方式。这是我的SQL ......

SELECT R.FinalProd
, MIN(r.seqnumber) Seq
, MIN(S.RollRecID) RID
, COUNT(DISTINCT S.RollRecID) Pieces
, (MIN(r.seqnumber) + COUNT(DISTINCT S.RollRecID) - 1) endd
FROM NYS1Reheat1 R INNER JOIN NYS1SawPieces S ON R.RecordID = S.RollRecID INNER JOIN TensileProducts T ON R.FinalProd = T.SQLProduct
where s.ShiftIdent = '05/22/15154D' and r.Location = 'HISTORY'
and datepart(hour,s.prodtime) > 17 and datepart(hour,s.prodtime) < 19
GROUP BY R.FinalProd, T.FootWeight
order by RID

我需要从1700开始,然后按小时到0600。 到目前为止,我的计划是&#34;循环&#34;通过代码12次。

谢谢, 道格

1 个答案:

答案 0 :(得分:0)

您可以交叉加入您的时间间隔:

;with loop12 as (
   select 17 as f, 19 as t union all
   select 19 as f, 21 as t union all
   ...
)
SELECT R.FinalProd
, MIN(r.seqnumber) Seq
, MIN(S.RollRecID) RID
, COUNT(DISTINCT S.RollRecID) Pieces
, (MIN(r.seqnumber) + COUNT(DISTINCT S.RollRecID) - 1) endd
, loop12.f 
FROM NYS1Reheat1 R 
INNER JOIN NYS1SawPieces S ON R.RecordID = S.RollRecID
INNER JOIN TensileProducts T ON R.FinalProd = T.SQLProduct
CROSS JOIN loop12
WHERE s.ShiftIdent = '05/22/15154D' and r.Location = 'HISTORY'
and datepart(hour,s.prodtime) > loop12.f and datepart(hour,s.prodtime) < loop12.t
GROUP BY R.FinalProd, T.FootWeight
order by RID, loop12.f