我有一个包含用户帐户权限的表,我正在尝试编写一个查询,为每个用户帐户组合返回一行。
这就是我所拥有的。
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”语句,但性能很糟糕。有没有人知道如何做到这一点?
感谢。
编辑:不幸的是,这必须在SQL 2000中运行。
答案 0 :(得分: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.
答案 1 :(得分: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
;
答案 2 :(得分:0)
使用PIVOT - 以下是一个示例:http://msdn.microsoft.com/en-us/library/ms177410.aspx