我有一个包含用户帐户权限的表,我正在尝试编写一个查询来为每个用户帐户组合返回一行。
这是我所拥有的。
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 中工作。
最佳答案
自从我使用 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.
关于sql-server - 将多行合并为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375397/