我有2张桌子,即。 Regtbl和Invoicetbl
Regtbl具有regid,createddatetime,isActive(bool),invoicetbl具有regid,invMonth,invYear,invUploadedDateTime。
我想创建一个查询,该查询将向我返回在给定日期范围内未提交发票的所有regid。
假设我想获得那些在一月至五月之间未提交发票的用户的记录。
下面是我尝试过的查询,但似乎无法正常工作。
Declare @MinYear int, @MaxYear int, @Minmonth smallint , @Maxmonth smallint
Set @MinYear = '2019'
Set @MaxYear = '2019'
Set @Minmonth = '01'
Set @Maxmonth = '05'
CREATE TABLE #TempTable(
PrimaryEnterpriseId nvarchar(50),
RegistrationNm nvarchar(50),
InvoiceMonth char(3),
InvoiceYear char(4))
While (@MinYear <= @MaxYear)
BEGIN
While (@Minmonth <= @Maxmonth)
BEGIN
INSERT INTO #TempTable Select distinct t1.primaryenterpriseid, t1.RegistrationNm, @Minmonth as InvoiceMonth, @MinYear as InvoiceYear
from regtbl t1
where NOT EXISTS(
SELECT t2.enterpriseid, t2.InvoiceMonth,t2.InvoiceYear,t2.RegistrationID
FROM invoicetbl t2
WHERE t1.registrationid=t2.registrationid and t2.InvoiceMonth = @Minmonth and t2.ApprovalStatus!='Rejected' )
and t1.DeregisteredInd=0 and t1.RegistrationType='Register' and t1.StatusInd=1
Set @Minmonth = @Minmonth + 1
END
SET @MinYear = @MinYear + 1
END
select * from #TempTable
DROP TABLE #TempTable
答案 0 :(得分:0)
Select distinct t1.primaryenterpriseid, t1.RegistrationNm
From regtbl t1
Left Outer Join invoicetbl t2
On t1.registrationid=t2.registration
Where t2.InvoiceMonth = @Minmonth
And t2.ApprovalStatus!='Rejected'
And t1.DeregisteredInd=0
And t1.RegistrationType='Register'
And t1.StatusInd=1
And t2.registration is null