2010-07-30 6 views
2

사용자 계정 권한이있는 테이블이 있는데 각 사용자 계정 조합에 대해 한 행을 반환하는 쿼리를 작성하려고합니다.여러 행을 하나의 행으로 결합

다음은 내가 가지고있는 것입니다.

CltKey AcctKey TranTypeID Access 
10  2499 10   0 
10  2499 11   1 
10  2499 12   1 
10  2764 10   1 
10  2764 11   1 
10  2764 12   0 

내가 원했던 바는 다음과 같습니다.

CltKey AcctKey TranTypeID1 Access1 TranTypeID2 Access2 TranTypeID3 Access3 
10  2499 10   0  11  1  12  1 
10  2764 10   1  11  1  12  0 

또는 이보다 더 좋은 점입니다.

CltKey AcctKey HasTranTypeID1 HasTranTypeID2 HasTranTypeID3 
10  2499 0    1    1 
10  2764 1    1    0  

자기 조인을 시도했지만 각 TranTypeID에 대해 여러 행을 계속 유지합니다. 하나는 0과 같고 다른 하나는 1과 같습니다. 또한 중첩 된 "Select"문을 사용하여 시도했지만 성능은 끔찍합니다. 누구든지이 작업을 수행하는 방법에 대한 아이디어가 있습니까?

감사합니다.

편집 : 불행하게도, 이것은 내가 SQLServer에 2000을 사용하기 때문에 그것은 잠시이었다 SQL 2000

+2

어떤 버전의 SQL Server가 있습니까? 2005+에는 PIVOT 구문이 있습니다. 하지만 동적 인 것은 아닙니다 ... –

답변

2

에서 작동하는, 그러나 이것은 아마 작동합니다.

create view has_access as 
select cltkey, acctkey, 
max(case when trantypeid = 10 and access = 1 
     then 1 else 0 end) as hastrantypeid1, 
max(case when trantypeid = 11 and access = 1 
     then 1 else 0 end) as hastrantypeid2, 
max(case when trantypeid = 12 and access = 1 
     then 1 else 0 end) as hastrantypeid3 
from table; 

을 다음이 당신에게 (cltkey, acctkey를) 말할 것이라고이

select cltkey, acctkey, 
max(hastrantypeid1) as hastrantypeid1, 
max(hastrantypeid2) as hastrantypeid2, 
max(hastrantypeid2) as hastrantypeid2 
from has_access 
group by cltkey, acctkey; 

주에서 결과를 얻을 수 (의 액세스 할 수 있습니다

select cltkey, acctkey, 
max(case when trantypeid = 10 and access = 1 
     then 1 else 0 end) as hastrantypeid1, 
max(case when trantypeid = 11 and access = 1 
     then 1 else 0 end) as hastrantypeid2, 
max(case when trantypeid = 12 and access = 1 
     then 1 else 0 end) as hastrantypeid3 
from table 
group by cltkey, acctkey; 

되지 않은 경우,이 시도 특정 유형) (cltkey, acctkey)의 해당 튜플에 대한 행이 특정 유형에 대한 액세스 권한이있는 경우. 즉, 기본적으로 행순입니다. OR입니다.

min(case when trantypeid = 10 
     then case when access = 1 
      then 1 else 0 end else null end) as hastrantypeid1, 
etc. 
+0

+1 : 피벗 쿼리의 가장 휴대 가능한 수단입니다. –

+0

감사합니다. 첫 번째 진술이 작동합니다. – Waylon

1
SELECT CltKey, AcctKey, 
    MAX(CASE TrantypeId WHEN 10 THEN Access ELSE NULL END) AS HasTranTypeID1, 
    MAX(CASE TrantypeId WHEN 11 THEN Access ELSE NULL END) AS HasTranTypeID2, 
    MAX(CASE TrantypeId WHEN 12 THEN Access ELSE NULL END) AS HasTranTypeID3 
FROM PermissionsTable 
GROUP BY CltKey, AcctKey 
ORDER BY CltKey, AcctKey 
; 
: 당신이 행 방향으로 AND을 원하는 경우 그 튜플에 대한 모든 행이 그 튜플에 대한 액세스 권한이 있어야합니다 경우

, 즉 액세스 할 수 있도록, 당신은이 작업을 수행해야합니다

관련 문제