我需要一个查询,它将根据表中的一组列比较返回SQL Server表中的重复行。我已经接近了这个:
DECLARE @startDate AS DATETIME = '9/1/2017';
DECLARE @endDate AS DATETIME = '9/2/2017';
WITH DupRecordSet AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY CCACaseId, Decision, DecisionDate, Extension, [Filename], Medicaid, MMISBillingNumber, NarrativeOfComments, NPIProviderId, OACNarrative, OHAdministrativeCode, PostSubmissionStateDate, PreSubmissionStateDate, ProviderID, ProviderRequestNarrative, RequestDate, ServiceTypeAuthRequest, Source, StateHearingDate, TypeOfRequest, UMTDPostSubmissionStateId, UMTDPreSubmissionRejectReasonId, UMTDPreSubmissionStateId ORDER BY (SELECT 0)) AS DuplicateRowNumber
FROM
CTSMember01.dbo.UMTDRecord
WHERE
DecisionDate BETWEEN @startDate AND @endDate
), DisplayRecordSet AS
(
SELECT
*
FROM
DupRecordSet
WHERE
DupRecordSet.DuplicateRowNumber > 1
)
SELECT *
FROM DisplayRecordSet;
但问题是这只包括“额外”行。换句话说,在找到3个重复行的情况下,此查询将返回第二行和第三行,但不返回第一行。我需要所有三行。
答案 0 :(得分:4)
您可以使用ROW_NUMBER
代替DECLARE @startDate AS DATETIME = '9/1/2017';
DECLARE @endDate AS DATETIME = '9/2/2017';
WITH
DupRecordSet
AS
(
SELECT *, COUNT(*) OVER (PARTITION BY CCACaseId, Decision, DecisionDate, Extension, [Filename], Medicaid, MMISBillingNumber, NarrativeOfComments, NPIProviderId, OACNarrative, OHAdministrativeCode, PostSubmissionStateDate, PreSubmissionStateDate, ProviderID, ProviderRequestNarrative, RequestDate, ServiceTypeAuthRequest, Source, StateHearingDate, TypeOfRequest, UMTDPostSubmissionStateId, UMTDPreSubmissionRejectReasonId, UMTDPreSubmissionStateId) AS DuplicateRowNumber
FROM CTSMember01.dbo.UMTDRecord
WHERE DecisionDate BETWEEN @startDate AND @endDate
),
DisplayRecordSet
AS
(
SELECT *
FROM DupRecordSet
WHERE DupRecordSet.DuplicateRowNumber > 1
)
SELECT *
FROM DisplayRecordSet;
:
{{1}}