我有一张下面给出的表格。在这里,还添加了一些数据。
CREATE TABLE [dbo].[ApplicationState](
[ID] [varchar](8) NULL,
[State] [int] NULL,
[subState] [int] NULL,
[SL] [int] NULL,
[CanView] [bit] NULL,
[CanEdit] [bit] NULL,
[CanSave] [bit] NULL,
[CanApproved] [bit] NULL,
[CanReject] [bit] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[ApplicationState] ([ID], [State], [subState], [SL], [CanView], [CanEdit], [CanSave], [CanApproved], [CanReject]) VALUES (N'00000001', 5, 2, 1, 1, 0, 0, 0, 0)
INSERT [dbo].[ApplicationState] ([ID], [State], [subState], [SL], [CanView], [CanEdit], [CanSave], [CanApproved], [CanReject]) VALUES (N'00000001', 5, 3, 1, 1, 0, 1, 0, 0)
INSERT [dbo].[ApplicationState] ([ID], [State], [subState], [SL], [CanView], [CanEdit], [CanSave], [CanApproved], [CanReject]) VALUES (N'00000001', 5, 4, 2, 1, 0, 0, 1, 1)
INSERT [dbo].[ApplicationState] ([ID], [State], [subState], [SL], [CanView], [CanEdit], [CanSave], [CanApproved], [CanReject]) VALUES (N'00000001', 5, 2, 2, 1, 1, 0, 0, 0)
需要优化查询(仅显示一行)才能获得以下结果:
ID | State | CanView | CanEdit | CanSave | CanApproved | CanReject
1 | 5 | 1 | 1 | 1 | 1 | 1
答案 0 :(得分:3)
根据您的评论,这似乎是您正在寻找的。如果不符合要求,您需要更好地阐明您的要求。
编辑:如果你的目标是按照ID和State进行分组,正如Ivan所说,那就这样做:
SELECT
ID,
State,
MAX(CAST(CanView AS INT)) AS CanView,
MAX(CAST(CanEdit AS INT)) AS CanEdit,
MAX(CAST(CanSave AS INT)) AS CanSave,
MAX(CAST(CanApproved AS INT)) AS CanApproved,
MAX(CAST(CanReject AS INT)) AS CanReject
FROM
dbo.ApplicationState
GROUP BY
ID,
State;
答案 1 :(得分:0)
根据您的输入和要求输出,我认为您希望任何值大于零,请考虑输出1。
SELECT
ID,
State,
Case when MAX(CanView) > 1 then 1 else 0 end AS CanView,
Case when MAX(CanEdit) > then 1 else0 end AS CanEdit,
MAX(CanSave) AS CanSave,
MAX(CanApproved) AS CanApproved,
MAX(CanReject) AS CanReject
FROM
dbo.ApplicationState
GROUP BY
ID,
State;
您可以为其他列
做同样的事情