2010-07-30 68 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.我也嘗試使用嵌套的「選擇」語句,但性能是可怕的。有沒有人有關於如何做到這一點的想法?

謝謝。

編輯:不幸的是,這個在2000年SQL

+2

對於哪個版本的SQL Server? 2005+具有'PIVOT'語法。但它不是動態的... – 2010-07-30 21:16:25

回答

2

工作這已經有一段時間,因爲我使用SQLServer 2000的,但是這可能會工作。

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; 

如果沒有,試試這個:

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; 

,然後從這個

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

注意,這會告訴你(cltkey,acctkey)讓您的結果訪問(的如果(cltkey,acctkey)的那個元組的任何行有訪問該特定類型的行。也就是說,它本質上是一個行的OR

如果所有行爲數組必須爲數組訪問訪問,也就是說,如果你想逐行AND,你需要這樣做:

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

+1:樞軸查詢的大多數可移植手段。 – 2010-07-30 21:31:31

+0

謝謝,第一個聲明的作品。 – Waylon 2010-08-02 13:49:58

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 
;