我回到了这个问题。这是我的表,其中包含一些记录:
CREATE TABLE [dbo].[test](
[reportID] [int] NOT NULL,
[caseID] [int] NOT NULL,
[carriedOver] [bit] NULL,
[oldReportID] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (304, 4, 1, NULL)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (305, 4, 0, NULL)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (306, 4, 1, 304)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (309, 4, 1, 306)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (311, 4, 0, NULL)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (312, 4, 1, 309)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (100, 1, 0, NULL)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (418, 8, 0, NULL)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (436, 8, 1, NULL)
GO
INSERT [dbo].[test] ([reportID], [caseID], [carriedOver], [oldReportID])
VALUES (438, 8, 0, 436)
GO
所需的输出如下:
对于CaseID = 4,我应该取回ReportID:304、306、309和312
对于CaseID = 1,我应该只返回ReportID:100
对于CaseID = 8,我应该只返回ReportID:418
当第一个报告及其结转内容一起结转时,基本上可以获得一串结转的reportID。如果第一个报告没有结转,则应仅返回该报告。
建议的解决方案是:
declare @caseID int = 4
SELECT t.reportID
FROM dbo.test t
WHERE ( exists ( SELECT 1 FROM dbo.test t1 WHERE t1.reportID = t.oldReportID and t1.caseID = @caseID ) or
exists ( SELECT 1 FROM dbo.test t2 WHERE t2.oldReportID = t.reportID and t2.caseID = @caseID ) )
and caseID = @caseID
ORDER BY 1 asc
这对于CaseID = 4正常工作,但对于CaseID = 1或CaseID = 8则失败。
有什么建议吗?
答案 0 :(得分:1)
我认为您可以通过以下查询解决问题
DECLARE @caseID INT = 4
DECLARE @ftrptID INT = (Select MIN(reportID) from dbo.test where caseID=@caseID )
if EXISTS(Select 1 from dbo.test where carriedOver=1 and reportID=@ftrptID)
BEGIN
SELECT t.reportID
FROM dbo.test t
WHERE ( exists ( SELECT 1 FROM dbo.test t1 WHERE t1.reportID = t.oldReportID and t1.caseID = @caseID ) or
exists ( SELECT 1 FROM dbo.test t2 WHERE t2.oldReportID = t.reportID and t2.caseID = @caseID ) )
and caseID = @caseID
ORDER BY 1 asc
END
ELSE
SELECT t.reportID
FROM dbo.test t
where reportID=@ftrptID