SQL:忽略一列时选择distinct

时间:2015-04-27 16:22:30

标签: sql sql-server

所以下面的查询工作得很好,除了一个主要的缺陷,pr.notes字段是文本,你不能区分文本,因为它不具有可比性,有没有办法让我仍然选择它?

SELECT * FROM (

    select distinct d.PhoneNum,d.sourcetable,N.FullName,C.fk_applicationid as ref,t.Subject,t.CreatedDate,pr.notes 
    , RANK() OVER ( PARTITION BY  N.FullName ORDER BY t.CreatedDate DESC ) AS iRank


    from Dial d
    join Database.dbo.DM_PhoneNumbers p on p.PhoneNum1 = d.PhoneNum collate latin1_general_CI_AS
    join Database.dbo.DM_PhoneNumbers on p.PhoneNum2 = d.PhoneNum collate latin1_general_CI_AS
    join Database.dbo.DM_ClientApplicants C on C.FK_ClientID = P.FK_ApplicationID
    join Database.dbo.DM_Names N on c.FK_ClientID = N.FK_ApplicationID
    join Database.dbo.Tasks T on T.FK_ApplicationID = c.FK_ApplicationID
    join database.dbo.dm_projects pr on pr.fk_applicationid = T.fk_applicationid
where c.FK_ClientID in (39157,39160)

) AS t 
WHERE t.iRank = 1

1 个答案:

答案 0 :(得分:1)

pr.notes转换为VARCHAR(MAX)NVARCHAR(MAX),具体取决于它所拥有的数据(我假设您使用的是SQL Server - 当我看到您的代码时,它就是这种情况)。

    SELECT * FROM (

        select distinct d.PhoneNum,d.sourcetable,N.FullName,C.fk_applicationid as ref,
        t.Subject,t.CreatedDate,CAST(pr.notes AS NVARCHAR(MAX)) AS notes, 
        RANK() OVER ( PARTITION BY  N.FullName ORDER BY t.CreatedDate DESC ) AS iRank

        from Dial d
        join Database.dbo.DM_PhoneNumbers p on p.PhoneNum1 = d.PhoneNum collate latin1_general_CI_AS
        join Database.dbo.DM_PhoneNumbers on p.PhoneNum2 = d.PhoneNum collate latin1_general_CI_AS
        join Database.dbo.DM_ClientApplicants C on C.FK_ClientID = P.FK_ApplicationID
        join Database.dbo.DM_Names N on c.FK_ClientID = N.FK_ApplicationID
        join Database.dbo.Tasks T on T.FK_ApplicationID = c.FK_ApplicationID
        join database.dbo.dm_projects pr on pr.fk_applicationid = T.fk_applicationid
    where c.FK_ClientID in (39157,39160)

    ) AS t 
    WHERE t.iRank = 1;