SQL从两列和两个表追加不同的值

时间:2018-06-25 18:00:42

标签: sql append

我正在尝试创建SQL代码,该代码从两列中获取不同的值并将其“追加”。我的意思是下表:

Account   Article
-----------------
   1        1
   1        2
   2        3

应产生以下结果:

Account   Article
-----------------
   1        1
   1        2
   1        3
   2        1
   2        2
   2        3

我正在使用一个联合在两个表中执行此操作,因此,想法是将两个表中所有唯一帐户号与两个表中所有唯一商品号的所有组合结合在一起。我想要一个子句,将两个表的订购日期限制在一年前。

到目前为止,我有:

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

问题在于,它仅在帐户和商品同时存在的情况下为我提供组合。我对使用with语句感到厌倦:

WITH temp1 AS 
(
     Select distinct cus_outnum 
     From table1
), temp2 AS
(
     Select distinct artnum 
     From table1
)
SELECT cus_outnum,artnum
FROM temp1, temp2, table1

非常需要蚂蚁的帮助!

2 个答案:

答案 0 :(得分:0)

这给出了预期的结果:

with cte1 as (Select distinct account from test)
,cte2 as (Select distinct article from test)
Select * from cte1 cross join cte2

模式:

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

答案 1 :(得分:0)

您需要cross加入:

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