2016-06-25 7 views
0

나는 불꽃이 뭐하는 거지에 따라 전체 행을 선택합니다어떻게 별개의 열

cityId PhysicalAddress  EmailAddress   ..many other columns of other meta info... 
1  b st     [email protected] 
1  b st     [email protected] <- some rows can be entirely duplicates 
1  a avenue    [email protected] 
2  c square    [email protected] 
2  d blvd    [email protected] 

이이 테이블에 기본 키가 없습니다 내가 각각 별개의 cityId을 기반으로 한 임의의 행을 잡아하려는

예 이것은 정답입니다.

cityId PhysicalAddress  EmailAddress  ..many other columns 
1  b st     [email protected] 
2  c square    [email protected] 

이것은 또한 정답입니다

cityId PhysicalAddress  EmailAddress  ..many other columns 
1  a avenue    [email protected] 
2  c square    [email protected] 

마음에 떠오르는 한 가지 방법은 group by을 사용하는 것입니다. 그러나, 그것은 다른 열에 집계 함수를 사용해야합니다. (예 : min()). 반면, 나는 단지 전체 행을 꺼내고 싶다.

답변

0
;WITH CTE AS 
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY cityId ORDER BY cityId) AS RN 
    FROM [TABLE_NAME] 
) SELECT * FROM CTE WHERE RN = 1 
0

SQL Server 2008 R2가 있지만 다른 DBMS에서 작동하는 방법을 찾으려고했습니다.

create table contacts(cityId int, PhysicalAddress varchar(max), EmailAddress varchar(max)) 

delete contacts 
insert contacts(cityId, PhysicalAddress, EmailAddress) /** ..many other columns of other meta info... */ 
values 
    (1, 'b st', '[email protected]') 
, (1, 'b st', '[email protected]')      /* some rows can be entirely duplicates */ 
, (1, 'a avenue', '[email protected]') 
, (2, 'c square', '[email protected]') 
, (2, 'd blvd', '[email protected]') 
, (3, 'e circuit', '[email protected]') 

-- using row_number() 

with c as (
     select *, row_number() over (partition by cityId order by cityId) as seqnum 
     from contacts 
    ) 
    select * from c 
    where seqnum = 1; 


-- Add a new identity column 

alter table contacts 
    add id int identity(1,1) 

select * from contacts where id in (select min(id) from contacts group by cityID) 

-- Variation: Create a copy into a temp table and add an identity column 
-- Note: It may not be possible to modify original table 

select * into #contacts from contacts 
alter table #contacts 
    add id int identity(1,1) 
select * from #contacts where id in (select min(id) from #contacts group by cityID) 

는 또한 newid()을 사용하여 계산 된 열을 사용하여 시도하지만 내 흥분이 단명 당신이 자체 테이블 조인 또는 테이블에 하위 쿼리를 사용할 때, 계산 열은 각 SELECT 재 계산되기 때문에되도록했다 작동하지 않았다. 계산 된 열 PERSISTED을 만들 수는 없습니다. newid()과 같은 비 결정적 식에는 사용할 수 없습니다. 주어진 행에 대해 호출 할 때마다 다른 결과를 반환합니다.