简体   繁体   中英

Getting multiple identical rows using group by in SQL Server

The code below returns:

DonorCenterDescription  Product         Pledge  
-----------------------------------------------
Avon                    Double Red      14
Avon                    Platelet        6
Avon                    Platelet        36
Avon                    Platelet        18
Avon                    Platelet        40
Avon                    Whole Blood     4
Avon                    Whole Blood     12
Avon                    Whole Blood     192

But I want only one row for each product (Double Red, Platelet, WholeBlood).

I know that I'm getting the extra rows because the table that has the product info has multiple rows for each product:

Select
    L.DonorCenterDescription,
    P.Product,
    Count(I.DonorID) * P.Frequency As Pledge
From
    HemaConnectDailyFiles.dbo.IPledgeCallCodes I 
Inner Join
    DonorCenterCodeAssignedToDonorsMaster C On I.DonorID = C.DonorID 
Inner Join
    MarketingTempTables.dbo.FixedDCDesc L On C.DonorCenterCode = L.DonorCenterCode 
Inner Join
    MarketingTempTables.dbo.PledgeKey2014 P On I.IPICCallCodes = P.Code
Where
    Left(I.IPICCallCodes, 4) = '2014'
Group By 
    L.DonorCenterDescription, P.Product, P.Frequency
Order By
    L.DonorCenterDescription, P.Product

But I don't know how to get to:

Avon    Double Red      14
Avon    Platelet        94
Avon    Whole Blood     208

You need some clarifying logic...these are not duplicate rows, they are rows that are being differentiated when you have P.Frequency in the group by statement.

When you have 5 rows for AVON platelet, it is recieving multiple values for pledge. You need logic to determine what value for p.frequency to use.

Edit : didn't see your end results. 2 alterations:

change pledge line to a full aggregate :

sum(Count(I.DonorID) * P.Frequency)  as pledge 

edit in : this may be what you are looking for...unsure if the sum(count() * field) is valid.

sum(I.DonorID * P.Frequency)

-- (I think this will achieve what you want...if not you'll have to clarify the logic in calculating pledge by the 2 columns DonorCenterDescription and Product

remove frequency from the group by statement

-- in the end, this is why you are getting the duplicate rows...this code is explicitly stating that L.DonorCenterDescription, P.Product, P.Frequency is a unique combination not just L.DonorCenterDescription, P.Product like you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM