我有一张表,每天都会按日期更新新发票行。但是,每个新的一天都将包含前几天的所有发票。 1-1-2017将包含截至1-1-2017的所有发票,但1-2-2017将包含所有新发票以及1-1-2017的发票。以下是一个例子。
我希望能够只显示2017年3月23日发布的新记录。我尝试使用此代码:
SELECT
a.[Date]
,b.[Date]
,a.[Inv Name]
,b.[Inv Name]
,a.[amt]
FROM
[Invoice Table] a LEFT JOIN
[Invoice Table] b ON a.[Inv Name]=b.[Inv Name]
WHERE
--a.[customer_industry]<>b.[customer_industry] AND
a.[Date] = '3/23/2017' AND
b.[Date] = '3/22/2017' AND
b.[Date] = IS NULL
当我运行时,我得到零结果。非常感谢任何帮助!
答案 0 :(得分:2)
首先,使用ISO标准格式表示日期。其次,当使用LEFT JOIN
时,除了第一个表之外的所有条件都进入ON
子句。否则,过滤掉非匹配行中的NULL
值。另外,= IS NULL
是无效的语法。
我想你打算:
SELECT a.[Date], b.[Date], a.[Inv Name], b.[Inv Name], a.[amt]
FROM [Invoice Table] a LEFT JOIN
[Invoice Table] b
ON a.[Inv Name] = b.[Inv Name] AND b.[Date] = '2017-03-22'
WHERE --a.[customer_industry]<>b.[customer_industry] AND
a.[Date] = '2017-03-23' AND
b.[Date] IS NULL;
但是,我认为这更简单地使用LAG()
编写:
select t.*
from (select t.*, lag(date) over (partition by [Inv Name] order by date) as prev_date
from [Invoice Table] t
) t
where date = '2017-03-23' and (prev_date is null or prev_date <> '2017-03-22')
答案 1 :(得分:0)
SELECT
a.[Date]
,b.[Date]
,a.[Inv Name]
,b.[Inv Name]
,a.[amt]
FROM
[Invoice Table] a LEFT JOIN
[Invoice Table] b ON a.[Inv Name]=b.[Inv Name]
where b.[Inv Name] Is null