SQL Server:根据SELECT的一列删除重复项

时间:2018-05-13 08:24:19

标签: sql-server

我有以下查询,效果很好。但是,数据存在问题,我需要从结果中删除重复的sVisitID。这是我正在使用的SELECT,屏幕截图显示了结果。我需要编辑选择以便仅返回其中一个副本。

SELECT 
    DISTINCT(MyReps.[sName]) as 'Rep Name',
    MyData.[sVisitID] as 'ID',
    CAST(MyData.[sDate] AS DATE) as 'Date',
    MyData.[sClientName] as 'Store Name',
    MyData.[sState] as 'Region',
    CAST(MyData.[sLatitudeStart] AS VARCHAR(100)) + ',' + CAST(MyData.[sLongitudeStart] as varchar(100)) as 'Map'
FROM
    (SELECT * 
     FROM [tblRepresentatives] 
     WHERE [sActive] = 'True') as MyReps
FULL OUTER JOIN 
    (SELECT  *
     FROM [tblVisits] 
     WHERE CAST([sDate] AS DATE) = CAST(GETDATE()-1 AS DATE)) AS MyData ON MyReps.[sName] = MyData.[sRepresentativeName]
WHERE 
    MyData.[sClientName] IS NOT NULL 
    AND [sDateAndTimeStart] <> [sDateAndTimeEnd]
ORDER BY 
    MyData.[sClientName] DESC

结果:

Result

2 个答案:

答案 0 :(得分:2)

另一种方法可能是使用ROW_NUMBER() PARTITION BY MyData.[sVisitID],如下所示。

SELECT * FROM
(
SELECT  (MyReps.[sName]) as 'Rep Name',
MyData.[sVisitID] as 'ID',
CAST(MyData.[sDate] AS DATE) as 'Date',
MyData.[sClientName] as 'Store Name',
MyData.[sState] as 'Region',
CAST(MyData.[sLatitudeStart] AS VARCHAR(100)) + ',' + CAST(MyData.[sLongitudeStart] as varchar(100)) as 'Map',
ROW_NUMBER() OVER (PARTITION BY MyData.[sVisitID] ORDER BY MyData.[sVisitID]) AS RN

FROM (
    SELECT * 
        FROM [tblRepresentatives] 
        WHERE [sActive] = 'True') as MyReps

        FULL OUTER JOIN (
            SELECT  *
                FROM [tblVisits] 
                WHERE CAST([sDate] AS DATE) = CAST(GETDATE()-1 AS DATE)) AS MyData

        On MyReps.[sName] = MyData.[sRepresentativeName]

        WHERE MyData.[sClientName] IS NOT NULL AND  [sDateAndTimeStart] <> [sDateAndTimeEnd]

)T
WHERE RN=1
ORDER BY T.[Store Name] DESC

答案 1 :(得分:0)

一种选择是使用localStorage来解析单个记录:

GROUP BY