1
感謝您花時間閱讀本文。SQL Server計數發生了一個變量值
我有一個ServiceDetails
表具有列狀
ID, ServiceID , ClientID... , Status ,IsFollowUp
,並進入了一個服務請求時,服務有
ID, Date , CityID, AreaID
現在,它的狀態是'pending', 'Completed','testing', or 'indeteriminent'
。
現在,最終用戶希望一個報告,
市,區,TotalServices,共完成且無後續,在第一隨訪共建成後,在第2次隨訪...,共完成了第五共完成隨動
我已經完成直到現在,總完成沒有followup
但我怎麼計算Completed
服務followups
計數。
CREATE TABLE #TEMP#(
[ID] int PRIMARY KEY IDENTITY,
[Area] varchar(250),
[City] varchar(250),
[Total] int,
[WithoutFollowup] int,
[FirstFollowup] int,
[SecondFollowup] int,
[ThirdFollowup] int,
[FourthFollowup] int,
[FifthFollowup] int
);
DECLARE @AreaID AS bigint = 0
DECLARE @CityID AS bigint = 0
DECLARE @AreaName AS nvarchar(250) = ''
DECLARE @CityName AS nvarchar(250) = ''
DECLARE @VCCTDetailsID AS bigint = NULL, @ClientID AS bigint = NULL
,@TotalTests as int, @WithoutFollowup as int, @FirstFollowup as int,@SecondFollowup as int, @ThirdFollowup as int, @FourthFollowup as int, @FifthFollowup as int
,@Org as varchar(250),@City as varchar(250)
DECLARE cur CURSOR FOR
SELECT Areas.ID, Areas.Name, Cities.ID, Cities.CityName
FROM [dbo].[Areas]
INNER JOIN [dbo].[AreaCities] ON Areas.ID = AreaCities.AreaID
INNER JOIN [dbo].[Cities] ON AreaCities.CityID = Cities.ID
INNER JOIN [dbo].[States] ON States.ID = Cities.StateID
INNER JOIN [dbo].[Countries] ON Countries.ID = States.CountryID
WHERE [Areas].[IsActive] = 1
AND [Cities].[IsActive] = 1
AND [Areas].[CountryID] = 168
OPEN cur
FETCH NEXT FROM cur INTO @AreaID, @AreaName, @CityID, @CityName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Total = (
SELECT COUNT(1)
FROM [dbo].[ServiceDetails]
INNER JOIN [dbo].[Services] ON [ServiceDetails].[ServiceID] = [Services].[ID]
Where [ServiceDetails].[Status] !='Testing'
AND [ServiceDetails].[Status] !='Pending'
AND [Services].[AreaID] = @AreaID
AND [Services].[CityID] = @CityID
GROUP BY [Services].[AreaID],[Services].[CityID]
)
SET @WithoutFollowup = (
SELECT COUNT(1)
FROM [dbo].[ServiceDetails]
INNER JOIN [dbo].[Services] ON [ServiceDetails].[ServiceID] = [Services].[ID]
Where [ServiceDetails].[Status] !='completed'
AND [ServiceDetails].[IsFollowUp] = 'false'
AND [Services].[AreaID] = @AreaID
AND [Services].[CityID] = @CityID
GROUP BY [Services].[AreaID],[Services].[CityID]
)
SET @FirstFollowup = (
SELECT COUNT(1)
FROM [dbo].[ServiceDetails]
INNER JOIN [dbo].[Services] ON [ServiceDetails].[ServiceID] = [Services].[ID]
Where [ServiceDetails].[Status] !='completed'
AND [ServiceDetails].[IsFollowUp] = 'True'
GROUP BY [Services].[AreaID],[Services].[CityID]
)
INSERT #TEMP# ([Org],[City],[Total],[WithoutFollowup],[FirstFollowup],[SecondFollowup],[ThirdFollowup],[FourthFollowup],[FifthFollowup])
VALUES(@AreaName,@CityName,@Total,@WithoutFollowup,@FirstFollowup,@SecondFollowup,@ThirdFollowup,@FourthFollowup,@FifthFollowup);
FETCH NEXT FROM cur INTO @AreaID, @AreaName, @CityID, @CityName
END
CLOSE cur
DEALLOCATE cur
SELECT * FROM #TEMP#
DROP TABLE #TEMP#
任何人都好嗎?我只想計算「followups」的「出現次數」,有多少客戶進行了「後續」,然後狀態已完成。 –