Reputation: 187
I have entries in a data table TableofDates comprising three fields; ProjectID (type = dbText), Start (type = dbDate) and Finish (type = dbDate):
TableofDates
ProjectID Start Finish
ABC 01/01/2018 09/09/2018
I wish to present the following dataset with individual DateA records (derived from [Start] in [TableofDates]) and DateB records (derived form [Finish] in [TableofDates])
ToD UNION
ProjectID DateA DateB
ABC 01/01/2018
ABC 09/09/2018
The following SQL Query produces almost the result required:
SELECT ProjectID,DateA, '' AS DateB
FROM DtA
UNION SELECT ProjectID, '' AS DateA,DateB
FROM DtB;
The problem I have is that the inserted null strings force the field data to type dbText.
If instead I insert Nulls, I get only the first date field reproduced:
SELECT ProjectID, DateA, Null AS DateB
FROM DtA
UNION SELECT ProjectID, Null AS DateA, DateB
FROM DtB;
yields:
ToD UNION
ProjectID DateA DateB
ABC 01/01/2018
ABC
Both parts of the Union work individually:
SELECT ProjectID,DateA, Null AS DateB
FROM DtA;
yields
ToD UNION
ProjectID DateA DateB
ABC 01/01/2018
While
SELECT ProjectID,Null AS DateA, DateB
FROM DtB;
Yields
ToD UNION
ProjectID DateA DateB
ABC 09/09/2018
Any ideas how I can create a union of TableofDates with inserted "Null" dates as required, and maintain Data Type of dbDate in the resultant dataset?
Upvotes: 1
Views: 380
Reputation: 32642
You can use a header row (a select statement that returns 0 records, but includes the correct types and labels)
SELECT CLng(1) As ProjectID, #2001-01-01# As DateA, #2001-01-01# As DateB
FROM MSysObjects
WHERE 1=0
UNION ALL
SELECT ProjectID, DateA, Null
FROM DtA
UNION ALL
SELECT ProjectID, Null, DateB
FROM DtB;
Your query doesn't work, because in Access, the first query of a union query determines the type and label of the field. Because the last column of the first query only contains Null
, Access can't determine a field type, and chooses the wrong one.
By using a query that doesn't return records, but sets the field type explicitly, you're avoiding that problem.
Note that the change from UNION
(which typecasts and checks for duplicates) to UNION ALL
(which doesn't do those things) also fixes the problem. So 2 solutions for the price of one.
Upvotes: 2
Reputation: 19737
A Union query will ignore field alias names except for those in the first SELECT statement.
A NULL value is less than any date value, so a descending sort will place the NULLS first.
This SQL produces your example output:
SELECT ProjectID, Start AS DateA, NULL AS DateB
FROM TableOfDates
UNION ALL SELECT ProjectID, NULL, Finish
FROM TableOfDates
ORDER BY ProjectID, DateA DESC
This table:
ProjectID Start Finish
ABC 01/01/2018 09/09/2018
DEF 01/02/2017 03/05/2018
Produced this result:
ProjectID DateA DateB
ABC 01/01/2018
ABC 09/09/2018
DEF 01/02/2017
DEF 03/05/2018
Upvotes: 0