SQL 請問怎樣按日期中斷分組(150分)

  • 主题发起人 主题发起人 colonel
  • 开始时间 开始时间
C

colonel

Unregistered / Unconfirmed
GUEST, unregistred user!
表結構如下:(記錄數沒有限制)<br>Date &nbsp; &nbsp; &nbsp; &nbsp; Total &nbsp; &nbsp;Type<br>2008-01-01 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; A<br>2008-01-02 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; A<br>2008-01-03 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; A<br>2008-01-05 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; A<br>2008-01-06 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; A<br>2008-01-07 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; A<br>2008-01-02 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; B<br>2008-01-03 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; B<br>2008-01-05 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; B<br>2008-01-06 &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; B<br>結果為<br>Type &nbsp; &nbsp;BeginDate &nbsp; &nbsp;EndDate &nbsp; &nbsp; &nbsp; Total<br>A &nbsp; &nbsp; &nbsp; 2008-01-01 &nbsp; 2008-01-03 &nbsp; &nbsp; &nbsp;3<br>A &nbsp; &nbsp; &nbsp; 2008-01-05 &nbsp; 2008-01-07 &nbsp; &nbsp; &nbsp;3<br>B &nbsp; &nbsp; &nbsp; 2008-01-02 &nbsp; 2008-01-03 &nbsp; &nbsp; &nbsp;2<br>B &nbsp; &nbsp; &nbsp; 2008-01-05 &nbsp; 2008-01-06 &nbsp; &nbsp; &nbsp;2
 
开始日期和结束日期怎么确定???
 
1、先按日期排序<br>2、从最小日期,找连续的下已日期,找到就做过标记<br>3、按标记group<br>可能要用存储过程来处理
 
一条sql难以实现
 
///先创建时间分割临时表<br>Create Table #TableName<br>&nbsp; &nbsp; (Type varchar(10) not null,<br>&nbsp; &nbsp; &nbsp;BeginDate Datetime not null,<br>&nbsp; &nbsp; &nbsp;EndDate DateTime not null)<br>///插入具体的记录<br>Insert #TableName <br>&nbsp; &nbsp; (Type,BeginDate,EndDate)<br>Values<br>&nbsp; &nbsp; ('A','2008-01-01','2008-01-03')<br>...... &nbsp; <br>///获取分组结果<br>Select Type,BeginDate,EndDate,Sum(Total) SumTotal<br>From (Select 记录表.*,BeginDate,EndDate<br>&nbsp; &nbsp; &nbsp; From 记录表,#TableName<br>&nbsp; &nbsp; &nbsp; Where 记录表.Type=#TableName.Type<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; And Date &gt;= BeginDate<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; And Date &lt;= EndDate<br>&nbsp; &nbsp; &nbsp; ) a<br>group by Type,BeginDate,EndDate<br>///删除临时表<br>Drop Table #TableName<br>///<br><br>以上未经测试!?
 
可以做的,不过要求结果的BeginDate和EndDate间隔必须是固定的,如必须是3天,否则没有规律,只能一条一条处理了。
 
不好意思,最近有點忙,這個問題我已經完成了:)<br>解決辦法是不需固定的日期作為開始時間,如果說是使用標記算是說中一半,<br>但怎麼使用呢,解決辦法就在這了,代碼我不粘出來了,公司代碼的結構有關,<br>也不想重寫吧,我就提個提示,如果還有不明白我可以再說說的:)<br>關鍵是使用IDENTITY(INT, 0, 1),Group by ,dbo.dateadd()函數
 
后退
顶部