【发布时间】:2015-06-03 20:41:28
【问题描述】:
我正在寻找一种查询表的有效方法。 表结构为:
CREATE TABLE [dbo].[CaseManager](
[CaseID] [int] IDENTITY(1,1) NOT NULL,
[SystemUserCreatedBy] [int] NULL,
[SystemUserAssignee] [int] NULL,
CONSTRAINT [PK_Case] PRIMARY KEY CLUSTERED
(
[CaseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
查询应返回每个 caseID 和用户 ID(用户 ID 可以是 SystemUserCreatedBy 或 SystemUserAssignee)位列,显示使用是 Createdby 还是 Assignee 我设法这样写:
select CaseID,UserID,
max(CaseUser.IsAssignee) as IsAssignee,
max(CaseUser.IsCreator) as IsCreator
FROM
(
select CMassignee.CaseID,
CMassignee.SystemUserAssignee as UserID,
1 as IsAssignee ,
0 as IsCreator
from CaseManager CMassignee
where CMassignee.SystemUserAssignee is not null
UNION
select CMCreator.CaseID,
CMCreator.SystemUserCreatedBy as UserID,
0 as IsAssignee ,
1 as IsCreator
from CaseManager CMCreator
where CMCreator.SystemUserCreatedBy is not null
) CaseUser
group by CaseID,UserID
我很确定有更好的方法来编写它,只需扫描该表一次。在该示例中,我只显示两列(SystemUserCreatedBy as SystemUserAssignee),但实际上我有五个需要添加。
请看数据示例:
SET IDENTITY_INSERT dbo.casemanager ON;
insert into casemanager(caseid,SystemUserCreatedBy,SystemUserAssignee)
values
(1,2222,3333)
SET IDENTITY_INSERT dbo.casemanager OFF;
在这种情况下,我希望得到:
CaseID UserID IsAssignee IsCreator
----------- ----------- ----------- -----------
1 2222 0 1
1 3333 1 0
(2 row(s) affected)
【问题讨论】:
-
“SystemUserCreatedBy 或 SystemUserAssignee”这是一个异或,总是只有一个不为空?
-
很高兴您添加了所需的输出...在您缺席期间对此进行了相当大的辩论:-)
-
SystemUserCreatedBy 和 SystemUserAssignee 是可为空的列。
-
可空列没有问题,问题是是否应该将像 (1,2222,3333) 这样的行拆分为 2 个结果行。现在你说清楚了。
-
现在下一个问题是:
SystemUserCreatedBy和SystemUserAssignee可以是CaseID的同一用户吗?
标签: sql sql-server tsql union window-functions