Reputation: 67
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!
Upvotes: 2
Views: 607
Reputation: 50163
You need cross
join :
select distinct t.Account, t1.Article
from table1 t cross join
(select distinct article from table) t1;
Upvotes: 0
Reputation: 1845
This gives the expected result:
with cte1 as (Select distinct account from test)
,cte2 as (Select distinct article from test)
Select * from cte1 cross join cte2
Schema:
Create table test(account int, article int);
Insert into test values(1,1);
Insert into test values(1,2);
Insert into test values(2,3);
Upvotes: 1