减去两个CTE的结果

时间:2016-02-25 23:43:16

标签: sql-server stored-procedures common-table-expression

所以我有这样的查询

Create Procedure sp_GetTotalTargetsCount
@userId int
AS
Begin
Create Table #RequestTargets
(
Name varchar(20),
Value int
)
Declare @rId int
Set @rId=0

Select @rId=r.RequestId From Requests r
Join RequestPipeline rp 
on r.RequestId=rp.RequestId
Join RequestStatus rs
on rp.RequestStatusId=rs.StatusId
Where rs.StatusDescription='In Progress.'

;With TotalCTE AS (Select Count(*) As TotalTargets FROM Targets Where InsertedByUserId=@userId),
FilteredCTE AS (Select Count(*) As FilteredTargets From RequestDetails Where RequestId=@rId)


Insert into #RequestTargets (Name,Value)
Select 'TotalTargets', Count(*) FROM Targets Where InsertedByUserId=@userId

Insert into #RequestTargets (Name,Value) 
Select 'UnderSurveillence', Count(*) From 
RequestDetails Where RequestId=@rId

Insert into #RequestTargets (Name,Value)
Values ('NotInSurveillence', (TotalCTE.TotalTargets-FilteredCTE.FilteredTargets)) --ERROR HERE it says Multipart identifier --  TotalTargets could not be bound
End

我想我可以在不使用CTE的情况下从其他计数()中减去一个计数()查询。有没有办法减去上面两个CTE的结果。请帮忙。

1 个答案:

答案 0 :(得分:0)

你不能这样使用CTE。尝试

;WITH totalcte
     AS (SELECT Count(*) AS TotalTargets
         FROM   targets
         WHERE  insertedbyuserid = @userId),
     filteredcte
     AS (SELECT Count(*) AS FilteredTargets
         FROM   requestdetails
         WHERE  requestid = @rId)
INSERT INTO #requesttargets
            (NAME,
             value)
SELECT 'NotInSurveillence',
       totalcte.totaltargets - filteredcte.filteredtargets
FROM   totalcte
       CROSS JOIN filteredcte  
FROM  TotalCTE CROSS JOIN FilteredCTE 

INFACT。 。您可以将所有内容组合成一个大的单个查询

 ;WITH totalcte
     AS (SELECT Count(*) AS TotalTargets
         FROM   targets
         WHERE  insertedbyuserid = @userId),
     filteredcte
     AS (SELECT Count(*) AS FilteredTargets
         FROM   requestdetails
         WHERE  requestid = @rId)
INSERT INTO #requesttargets
            (NAME,
             value)
SELECT 'NotInSurveillence',
       totalcte.totaltargets - filteredcte.filteredtargets
FROM   totalcte
       CROSS JOIN filteredcte
UNION ALL
SELECT 'TotalTargets',
       totalcte.totaltargets
FROM    totalcte
UNION ALL
SELECT 'UnderSurveillence',
       filteredcte.filteredtargets  
FROM   filteredcte