How do you SELECT several columns with one distinct column

半城伤御伤魂 提交于 2019-12-12 21:32:04

问题


Objective: using SqlServer 2005, Select multiple columns, but ensure that 1 specific column is not a duplicate

Issue: The following code does not remove the duplicates. The field that has duplicates is email.

SELECT DISTINCT 
           email,
           name,
           phone
FROM
    database.dbo.table
WHERE
    status = 'active'
GROUP BY
    email,
    name,
    phone

Thank you in advance for any comments, suggestions or recommendations.


回答1:


It removes email duplicates but you have to decide which name, phone you need. The result is based on name, phone sort order.

WITH cl
as
(
SELECT email, name, phone, ROW_NUMBER() OVER(PARTITION BY email ORDER BY name, phone) rn
FROM
    database.dbo.table
WHERE
    status = 'active')

select *
from cl
where rn =1  



回答2:


This is a way of doing it

DECLARE @Table AS TABLE
(email NVARCHAR(100), name NVARCHAR(100), phone NVARCHAR(100))

INSERT INTO @Table
        ( email , name , phone)
VALUES  ( N'fred', -- email  - nvarchar(100)
          N'bob', -- name - nvarchar(100)
          N'steve'  -- phone- nvarchar(100)
          )

          INSERT INTO @Table
        ( email , name , phone)
VALUES  ( N'fred', -- email - nvarchar(100)
          N'bob2', -- name - nvarchar(100)
          N'ste1ve'  -- phone- nvarchar(100)
          )

          INSERT INTO @Table
        ( email , name , phone)
VALUES  ( N'fred1', -- email - nvarchar(100)
          N'bob3', -- name - nvarchar(100)
          N'steve3'  -- phone- nvarchar(100)
          )


          SELECT email , MAX(name ) c2, MAX(col3) c3 FROM @Table GROUP BY email 


来源:https://stackoverflow.com/questions/19034283/how-do-you-select-several-columns-with-one-distinct-column

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