我有以下2组数据,我想将它组合成一整套(总结其中一列)。在此示例中,仅显示了1个项目。
第1集(主表):
start_date |item
2013-10-01 | 1
2013-10-15 | 1
2013-10-25 | 1
第2集(详细信息表):
working_date | item_no | qty
2013-10-03 | 1 | 2
2013-10-05 | 1 | 6
2013-10-18 | 1 | 3
2013-10-23 | 1 | 4
2013-10-27 | 1 | 6
2013-10-28 | 1 | 3
然后,我想根据开始日期将详细信息表中的数据与主表一起分组,并将数量总结如下:
决赛桌(结果):
starting_date | item_no | total_qty
2013-10-01 | 1 | 8
2013-10-15 | 1 | 7
2013-10-25 | 1 | 9
我很困难的是,我不知道如何在总和数量之前将working_date匹配到starting_date范围来对数量求和。
换句话说,我需要总结从2013-10-01到2013-10-14,2013-10-15到2013-10-24和2013-10-25到2013-10-31的数量
答案 0 :(得分:0)
你的问题并不完全清楚,但这应该足以成为你工作的一个例子。
SELECT master_table.starting_date,
details_table.item_no,
SUM(details_table.qty)
FROM master_table
JOIN details_table
ON master_table.item_no = details_table.item_no
GROUP BY master_table.starting_date,
details_table.item_no
答案 1 :(得分:0)
declare @startDate Datetime
set @startDate=DATEADD(month,-2,GETDATE()) -- set the startdate 2 months before today
declare @endDate Datetime
set @endDate=GETDATE() -- set the ending date equal to current datetime
declare @DaysStep int
set @DaysStep=10 -- set the step from day to the next day equal to 10 days.
-- so if today is 12/01/2013 the next day will be 12/11/2013
declare @results table (starting_date Datetime, item_no int, total_qty int)
while @startDate<@endDate
begin
insert into @results
select starting_date, item_no, sum(qty) as total_qty
from master as m
inner join detail as d
on m.item_no=d.item_no
where startingDate between @starDate and DATEADD(Days, @DaysStep, @startDate)
@startDate=DATEADD(Days, @DaysStep, @startDate)
end
select *
from @results
我想你用的是mssql。否则你应该将上面的代码更改为你的sql方言。您也可以根据需要设置@startDate,@ endDate和@DaysStep。
答案 2 :(得分:0)
对于详细信息表中的每个记录,您需要从主表中查找最接近的上一个日期。一旦找到,只需在该日期汇总。
select starting_date, sum(qty)
from (
select working_date,
item_no,
qty,
(select max(master_table.starting_date)
from master_table
where master_table.starting_date <= details_table.working_date
and master_table.item_no = details_table.item_no
) as starting_date
from details_table
) as modfied_table
group by starting_date
order by starting_date;
答案 3 :(得分:0)
这对你有用:
SELECT start_date, item_no, sum(qty) as qty
FROM #mastertable as aa INNER JOIN #detailtable as bb ON aa.item = bb.item_no
WHERE (start_date <= working_date
AND working_date < (SELECT TOP 1 start_date FROM #mastertable as innerT WHERE innerT.start_date > aa.start_date))
OR (working_date >= (SELECT TOP 1 start_date FROM #mastertable as innerT ORDER BY innerT.start_date DESC)
AND start_date = (SELECT TOP 1 start_date FROM #mastertable as innerT ORDER BY innerT.start_date DESC))
GROUP BY start_date, item_no
ORDER BY start_date