问题
I'm using Microsoft Access and I want to create a query that duplicates each row pulled in from a table with an extra field added on counting up one day between a given start and end date.
So if there's 4 days between the start and end date there's 4 duplicate rows returned for each record with only difference being the added date field counting up 1 day.
Is this actually possible to do?
回答1:
This task is fairly easy if you have a calendar table which includes a row for each date you need. (See this Stack Overflow answer for other reasons why a calendar table can be useful.) Without such a table, this task is not practical with Access SQL.
Using my calendar table and this sample data in YourTable ...
fld1 start_date end_date
---- ---------- ----------
a 12/26/2013 12/26/2013
b 12/27/2014 12/28/2014
c 1/1/2014 1/3/2014
d 1/4/2014 1/1/2014
... the query below gave me this output.
fld1 start_date end_date added_date
---- ---------- ---------- ----------
a 12/26/2013 12/26/2013 12/26/2013
b 12/27/2014 12/28/2014 12/27/2014
b 12/27/2014 12/28/2014 12/28/2014
c 1/1/2014 1/3/2014 1/1/2014
c 1/1/2014 1/3/2014 1/2/2014
c 1/1/2014 1/3/2014 1/3/2014
Notice the "d" row was not included in the output because end_date
was earlier than start_date
in that row. You can include a table-level validation rule to enforce the requirement that start_date
<= end_date
in every row.
SELECT
y.fld1,
y.start_date,
y.end_date,
c.the_date AS added_date
FROM
tblCalendar AS c
INNER JOIN YourTable AS y
ON
c.the_date >= y.start_date
AND c.the_date <= y.end_date
ORDER BY
y.fld1,
c.the_date;
来源:https://stackoverflow.com/questions/20923437/duplicate-each-row-pulled-in-and-add-an-extra-field-counting-up-one-day-between