删除t-sql查询结果中的重复行

时间:2014-03-27 11:40:55

标签: sql sql-server tsql sql-server-2005

我在下面有一些T-SQL,我遇到的问题是每行返回两次具有相同的值。如何确保每个都返回一次或强制选择Distinct

;WITH CTE_ReportDetails
AS (
    SELECT 
        CASE(GROUPING(M.Acronym))
            WHEN 0 THEN [Acronym]
            WHEN 1 THEN 'GRAND TOTAL'
            END AS [Company],

        CASE(GROUPING(DC.Name))
            WHEN 0 THEN DC.[Name]
            WHEN 1 THEN 'N/A'
            END AS [CatName],

        CASE(GROUPING(D.[Name]))
            WHEN 0 THEN D.[Name]
            WHEN 1 THEN 'Total '+ '('+DC.[Name]+')'
            END AS [Name],

        SUM(ISNULL(B.One, 0)) AS One,
        SUM(ISNULL(B.Two, 0)) AS Two,
        SUM(ISNULL(B.Three, 0)) AS Three,
        ISNULL(B.Description, '') AS Description,
        GROUPING(M.Acronym) AS CompanyGrouping,
        GROUPING(DC.[Name]) AS DCatGroup,
        GROUPING(D.[Name]) AS DGroup
    FROM Dee D 
        INNER JOIN DeeCategory DC ON D.DeeCategoryId = DC.DeeCategoryId
        INNER JOIN BD B ON B.DeeId = D.DeeId
        INNER JOIN Report R ON R.RptId = B.RptId
        INNER JOIN Company M ON R.CompanyId = M.CompanyId                
    WHERE (R.ReportDate >= @StartDate AND R.ReportDate <= @EndDate) AND (R.CompanyId IN (SELECT DATA FROM SPLIT(@CompanyIds,',')))
    GROUP BY M.Acronym, DC.Name, D.Name,B.Description
    WITH ROLLUP
)
SELECT Company, Name As [Dee], 
        One, 
        Three, 
        Two, 
        (One + Three + Two) AS Total,
        Description
FROM CTE_ReportDetails

1 个答案:

答案 0 :(得分:0)

您的报告应具有group by的唯一值组合。因此,这四列应该是唯一的:

GROUP BY M.Acronym, DC.Name, D.Name,B.Description

如果我不得不猜测,你会得到重复项,因为B.Description表中的B重复了。我建议将其从GROUP BY中移除并更改此行:

    ISNULL(B.Description, '') AS Description,

    ISNULL(max(B.Description), '') AS Description,