2010-12-08 110 views
0

我需要得到幾個列形式的SQL查詢。然後我必須通過一列的「不同」值來過濾這個答案,但是在輸出中我需要具有所有列,而不僅僅是這些值必須是不同的。有誰能夠幫助我?按條款排序對我來說不是一個答案。如何按一列的值過濾行?

A,B,C,D 
E,F,G,H 
I,J,C,L 
M,N,Z,H 

上面是一個簡單的行輸出。請看第3欄。假設我們不知道我們有多少行。我只需要選擇第三列中具有不同值的行。 (C,G,Z) - 我們需要從「C」行過濾任何人。

+0

您可以發佈您的查詢和/或表的定義? – 2010-12-08 20:25:14

回答

3

我已經任意選擇使用col1打破col3上的關係。您可以調整partitionorder by部分以滿足您的需求。

/* Set up test data */ 
declare @test table (
    col1 char(1), 
    col2 char(1), 
    col3 char(1), 
    col4 char(1) 
) 

insert into @test 
    (col1, col2, col3, col4) 
    select 'A','B','C','D' union all 
    select 'E','F','G','H' union all 
    select 'I','J','C','L' union all 
    select 'M','N','Z','H' 

/* Here's the query */ 
;with cteRowNumber as (
    select col1, col2, col3, col4, 
      row_number() over (partition by col3 order by col1) as RowNumber 
     from @test 
) 
select col1, col2, col3, col4 
    from cteRowNumber 
    where RowNumber = 1 

返回

col1 col2 col3 col4 
---------------------------- 
A  B  C  D 
E  F  G  H 
M  N  Z  H 
0

ROLL UPCUBE可能對您的問題有所幫助,因爲它們可以基於GROUP BY彙總(即小計)數據,並仍然返回單個行。