Select a subgroup of records by one distinct colum

2019-08-01 19:04发布

问题:

Sorry if this has been answered before, but all the related questions didn't quite seem to match my purpose.

I have a table that looks like the following:

ID  POSS_PHONE    CELL_FLAG
=======================
1   111-111-1111  0
2   222-222-2222  0
2   333-333-3333  1
3   444-444-4444  1

I want to select only distinct ID values for an insert, but I don't care which specific ID gets pulled out of the duplicates.

For Example(a valid SELECT would be):

1   111-111-1111  0
2   222-222-2222  0
3   444-444-4444  1

Before I had the CELL_FLAG column, I was just using an aggregate function as so:

SELECT ID, MAX(POSS_PHONE)
FROM TableA
GROUP BY ID    

But I can't do:

SELECT ID, MAX(POSS_PHONE), MAX(CELL_FLAG)...

because I would lose integrity within the row, correct?

I've seen some similar examples using CTEs, but once again, nothing that quite fit.

So maybe this is solvable by a CTE or some type of self-join subquery? I'm at a block right now, so I can't see any other solutions.

回答1:

Just get your aggregation in a subquery and join to it:

SELECT a.ID, sub.Poss_Phone, CELL_FLAG
FROM TableA as a
INNER JOIN (SELECT ID, MAX(POSS_PHONE) as [Poss_Phone]
            FROM TableA
            GROUP BY ID) Sub
    ON Sub.ID = a.ID and SUB.Poss_Phone = A.Poss_Phone

This will keep integrity between your non-aggregated fields but still give you the MAX(Poss_Phone) per ID.