昨天发布了一个有关SQL append distinct values from two columns and two tables的问题,并产生了以下代码:
with cte1 as
(Select Distinct "Tra.".cus_outnum As "account number" from table1 "Tra." Where "Tra.".invdat >= DATEADD(year, -1, GETDATE())
union
Select Distinct "Sal.".outnum As "account number" From table2 "Sal." Where "Sal.".deldat>= DATEADD(year, -1, GETDATE()))
,cte2 as
(Select Distinct "Tra.".artnum As "article number" from tabel1 “Tra.” Where "Tra.".invdat >= DATEADD(year, -1, GETDATE())
union
Select Distinct ISNULL("Sal.".org_artnum, "Sal.".artnum) As "article number" From table2 "Sal." Where "Sal.".deldat>= DATEADD(year, -1, GETDATE()))
Select * from cte1 cross join cte2
它会生成一张表格,其中包含来自两个不同表格的帐号和商品编号的所有不同组合,这些表格的订购时间晚于一年前。
我要努力解决的下一个对象是在两个新列中包括最新和第二次购买日期。如果未对帐户和商品的任何组合进行购买,则结果应为null(空白)。并且最晚/第二个最晚日期(即最大日期)应该来自一个表或另一个表。最终结果应遵循以下原则:
<table><tbody><tr><th>Account</th><th>Article</th><th>Latest Date</th><th>Second to latest Date</th></tr><tr><td>1</td><td>1</td><td>26.06.2018</td><td>13.03.2018</td></tr><tr><td>1</td><td>2</td><td>15.05.2018</td><td>Blank (no purchase)</td></tr><tr><td>2</td><td>1</td><td>23.06.2018</td><td>30.06.2017</td></tr><tr><td>2</td><td>2</td><td>Blank (no purchase)</td><td>Blank (no purchase)</td></tr></tbody></table>
非常感谢您提供的所有帮助,非常感谢!
答案 0 :(得分:0)
部分伪装。要获得更多详细的帮助,请提供db-fiddle。
SELECT
a.Account as Account,
b.Article as Article,
(<SUBSELECT> MAX(DATE) FROM ... WHERE ... ) as LatestDate,
(<SUBSELECT> MAX(DATE) FROM ... WHERE ... < LatestDate ) as 'SecondToLatestDate')
FROM
accounts a JOIN articles b
+ some IFNULL's