2013-07-02 2 views
1

검토해 주셔서 감사합니다. 나는 도움을 절실히 필요로하고 아래의 질문에 명확한 문제가 발생했습니다 ...여러 개의 키 값의 순열을 식별하는 방법

SQL 2008을 사용하면 테이블이 5 개의 열로 설정되어 있습니다.

데이터를 효과적으로 다음과 같습니다 : 같은 column1 값이 기록에 대한

column1 column2 column3 column4 column5 
T1  N1  A1  L1  S1 
T1  N2  A2  L2  S4 
T1  N2  A3  L2  S2 
T1  N2  A1  L2  S4 
T2  N6  A3  L3  S2 
T2  N7  A3  L3  S4 
T2  N7  A3  L4  S4 
... 

, 나는 column5을 통해 column2의 각각의 고유 한 순열을 식별 할 수 있습니다. 1

얼마나 많은 기록 곳

column1 is the same value and 
column2 is the same value and 
column3 is the same value and 
column4 is the same value and 
column5 is different 

다음

사례 2

존재

케이스 :

는이 같은 질문에 대답 할 0

column1 is the same value and 
column2 is the same value and 
column3 is the same value and 
column4 is different and 
column5 is the same value 

다음

사례 3

column1 is the same value and 
column2 is the same value and 
column3 is the same value and 
column4 is different and 
column5 is different 

등등. 감사!

답변

0

흠. 만약 당신이 그것을 손으로하고 싶다면, 복수 키를 가진 group by 같은 것을해야합니다. 예 : 케이스 1의 경우 다음과 같이해야합니다.

select column1,column2,column3, column4, count(column5) group by column1,column2,column3, column4 

이렇게하면 column1-column4의 고유 한 조합마다 고유 한 레코드가 제공됩니다. 별개의 것을 원하면 사전 처리를해야 할 수도 있습니다.

보다 유연하게하려면 그룹별로 수행하는 저장 프로 시저가 해결책이 될 수 있습니다.

+0

당신은 'count (distinct column5)'를 사용할 수 있습니다. –

+0

테스트하고보고 할 것입니다. 고맙습니다. –

1

원하는 순열 테이블을 설정하고 쿼리에 case 로직을 설정하여 하나의 쿼리에서이 작업을 수행 할 수 있습니다.

다음은 세 개의 열이있는 예입니다.

with t as (
     select 'a' as a, 'b' as b, 'c' as c union all 
     select 'a', 'b', 'd' union all 
     select 'e', 'b', 'd' 
    ), 
    perms as (
     select 1 as col1, 1 as col2, 1 as col3 union all 
     select 1, 1, 0 union all 
     select 1, 0, 0 union all 
     select 0, 1, 1 union all 
     select 0, 1, 0 union all 
     select 0, 0, 1 
    ) 
select (case when p.col1 = 1 then a end) as col1, 
     (case when p.col2 = 1 then b end) as col2, 
     (case when p.col3 = 1 then c end) as col3, 
     count(*) 
from t cross join 
    perms p 
group by (case when p.col1 = 1 then a end), 
     (case when p.col2 = 1 then b end), 
     (case when p.col3 = 1 then c end) 
+0

고든 고마워, 나는 이것을 잘보고 다시보고 할 것이다. 매우 도움이된다! –

관련 문제