尝试编写一个查询来指定客户是否已完成特定列的两种类型

psj*_*j01 3 sql sql-server

我下面有这张表(resedtl)...

它包含有关客户及其 resType 及其状态的信息。我试图确定客户是否已完成(状态 = 完成)两种类型的“RES”或仅完成一种或仅两种。

在此输入图像描述

CREATE TABLE [dbo].[resedtl](
[CustId] [int] NOT NULL,
[RESType] [nchar](10) NULL,
[note] [varchar](50) NULL,
[status] [varchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[resedtl] ([CustId], [RESType], [note], [status]) VALUES (123, N'1         ', N'test', N'done')
GO
INSERT [dbo].[resedtl] ([CustId], [RESType], [note], [status]) VALUES (123, N'2         ', N'test2', N'done')
GO
INSERT [dbo].[resedtl] ([CustId], [RESType], [note], [status]) VALUES (124, N'1         ', N'test', N'done')
GO
INSERT [dbo].[resedtl] ([CustId], [RESType], [note], [status]) VALUES (124, N'2         ', N'tests', N'no')
GO
INSERT [dbo].[resedtl] ([CustId], [RESType], [note], [status]) VALUES (125, N'1         ', N'test', N'done')
GO
INSERT [dbo].[resedtl] ([CustId], [RESType], [note], [status]) VALUES (126, N'2         ', N'test', N'done')
GO
Run Code Online (Sandbox Code Playgroud)

我想返回这样的内容,如果 custId 已为 resType 1 和 2 完成,那么我想返回两者。否则只有一个或两个。

在此输入图像描述

到目前为止,我的查询写如下......

  select distinct  t.CustId, case when (
 select top 1 rd.CustId from resedtl rd
 where rd.CustId = t.CustId
 and rd.CustId in (
   select rd.CustId from resedtl rd
  where rd.status ='done'
  and rd.RESType = 1
  and rd.CustId = t.CustId
 )
 and rd.CustId in (
    select rd.CustId from resedtl rd
  where rd.status ='done'
  and rd.RESType = 2
  and rd.CustId = t.CustId
 )
 ) = t.CustId then 'both'
 when

 (
  select top 1 rd.CustId from resedtl rd
 where rd.CustId = t.CustId
 and rd.CustId in (
   select rd.CustId from resedtl rd
  where rd.status ='done'
  and rd.RESType = 1
  and rd.CustId = t.CustId
 )
 and rd.CustId not in (
    select rd.CustId from resedtl rd
  where rd.status ='done'
  and rd.RESType = 2
  and rd.CustId = t.CustId
 )
 ) = t.CustId then 'just one'

 when

 (
  select top 1 rd.CustId from resedtl rd
 where rd.CustId = t.CustId
 and rd.CustId not in (
   select rd.CustId from resedtl rd
  where rd.status ='done'
  and rd.RESType = 1
  and rd.CustId = t.CustId
 )
 and rd.CustId  in (
    select rd.CustId from resedtl rd
  where rd.status ='done'
  and rd.RESType = 2
  and rd.CustId = t.CustId
 )
 ) = t.CustId then 'just two'
 else 'None'
 end as result from resedtl t
 where t.CustId in (123,124,125,126)
Run Code Online (Sandbox Code Playgroud)

我想知道这是否是最好的方法,或者是否有更好的解决方案。

我的查询似乎过于复杂。

Dan*_*lor 5

select   Custld
        ,case when min(chk) <> max(chk) then 'both' 
              when min(chk) =  1        then 'just one' 
              when min(chk) =  2        then 'just two'
                                        else 'none' end as "result"
        
from     (
          select  *
                  ,case status when 'done' then RESType end as chk
          from    t
         ) t
group by Custld
Run Code Online (Sandbox Code Playgroud)
库斯特德 结果
123 两个都
124 只有一个
125 只有一个
126 只有两个

小提琴