admin

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

sql

我正在尝试创建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

蚂蚁的帮助将非常有必要!


阅读 177

收藏
2021-07-01

共1个答案

admin

这给出了预期的结果:

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);
2021-07-01