Question

I have a some T-SQL below and i am facing a problem where each row is being returned twice with the same values. How can ensure each is returned once or force a select 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
Was it helpful?

Solution

Your report should have a unique combinations of values from the group by. So, these four columns should be unique:

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

If I had to guess, you are getting duplicates because B.Description is duplicated in the B table. I would suggest removing it from the GROUP BY and changing this line:

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

to

    ISNULL(max(B.Description), '') AS Description,
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top