I'm trying to create SQL code that takes the distinct values from two columns and “appends” them. By that, I mean that that the following table:
Account Article
-----------------
1 1
1 2
2 3
Should produce the following result:
Account Article
-----------------
1 1
1 2
1 3
2 1
2 2
2 3
I'm doing this from two tables using a union, so the idea is to get all combination of all unique account numbers in both tables with all unique article numbers in both tables. And I want a clause that limits both tables to a order date later then one year ago.
So far I have:
Select Distinct
"Tra.".cus_outnum As "account number",
"Tra.".artnum As "article number"
From
(table1) "Tra."
Where
"Tra.".invdat >= DATEADD(year, -1, GETDATE())
Union
Select Distinct
"Sal.".outnum As "account number",
"Sal.".artnum As "article number"
From
(table2) "Sal."
Where
"Sal.".deldat>= DATEADD(year, -1, GETDATE())
Problem is that it only gives me the combination where both account and article exist. I have unsuccessfully tired to do it with a with statement:
WITH temp1 AS
(
Select distinct cus_outnum
From table1
), temp2 AS
(
Select distinct artnum
From table1
)
SELECT cus_outnum,artnum
FROM temp1, temp2, table1
Ant help would be much obliged!