我有一個created_date
(時間戳)在我的一個表上,它也有一個項目的duration
列,我需要加入另一個表,只有first_day_of_month
列有每個月的第一天,以及其他相關信息。使用日曆表生成數據的歷史視圖
表1
id project_id created_date duration
1 12345 01/01/2015 10
2 12345 20/10/2015 11
3 12345 10/04/2016 13
4 12345 10/08/2016 15
表2
project_id month_start_date
12345 01/01/2015
12345 01/02/2015
12345 01/03/2015
12345 01/04/2015
...
12345 01/08/2016
預期結果
project_id month_start_date duration
12345 01/01/2015 10
12345 01/02/2015 10
...
12345 01/10/2015 11
12345 01/11/2015 11
...
12345 01/04/2016 13
12345 01/05/2016 13
12345 01/06/2016 13
...
12345 01/08/2016 15
我希望能夠噸o歷史上列出我的第二張表中列出的數據。因此,基本上我希望查詢返回與month_start_date
相關的相同的duration
,以便值重複,直到滿足另一個dateadd(month,datediff(month,0,created_date),0) = first_day_of_month
...等等。
這是我的查詢:本
select table2.project_name,
table2.month_start_date,
table1.duration,
table1.created_date
from table1 left outer join table2
on table1.project_id=table2.project_id
where dateadd(month,datediff(month,0,table1.created_date),0)<=table2.month_start_date
group by table2.project_name,table2.month_start_date,table1.duration,table1.created_date
order by table2.month_start_date asc
,但我得到重複記錄:
結果我得到
project_id month_start_date duration
12345 01/01/2015 10
12345 01/02/2015 10
...
12345 01/10/2015 10
12345 01/10/2015 11
...
12345 01/04/2016 10
12345 01/04/2016 11
12345 01/04/2016 13
...
12345 01/08/2016 10
12345 01/08/2016 11
12345 01/08/2016 13
12345 01/08/2016 15
誰能幫助?
謝謝!
添加一些示例表數據和預期結果。同時向我們展示您當前的查詢嘗試! – jarlh
我會補充說,你現在擁有的表格模式將有所幫助。 –
我編輯了這篇文章:) – Synamoon