SQL append distinct values from two columns and two tables

拜拜、爱过 提交于 2019-12-10 22:14:22

问题


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!


回答1:


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);



回答2:


You need cross join :

select distinct t.Account, t1.Article
from table1 t cross join
     (select distinct article from table) t1;


来源:https://stackoverflow.com/questions/51029389/sql-append-distinct-values-from-two-columns-and-two-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!