sql-server - 将多行合并为一行

标签 sql-server t-sql sql-server-2000 pivot

我有一个包含用户帐户权限的表,我正在尝试编写一个查询来为每个用户帐户组合返回一行。

这是我所拥有的。

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/

相关文章:

SQL 更新查询

sql-server - 什么是 SQL Server 模块?

sql-server - 在 SQL Server 上使用 varchar(MAX) 与 TEXT

sql - 我如何需要将 ID 和名称传递给变量并执行过程

sql - Xquery 将 XML 标签解析为列

sql-server - 有什么方法/工具可以识别 SQL 服务器中的估计查询运行时间

delphi - 如何忽略TQuery中的一些参数

sql-server - SQL Server 存储过程语法错误

SQL - 如何检索一列中排名最高的行,而另一列中具有多个重复行

mysql - 从 MySQL 到 MS SQL,所有列都无效?