Select a subgroup of records by one distinct column

半世苍凉 提交于 2019-12-11 04:32:22

问题


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.



来源:https://stackoverflow.com/questions/6628900/select-a-subgroup-of-records-by-one-distinct-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!