gpt4 book ai didi

sql - 尝试编写查询以指定客户是否完成了特定列的两种类型

转载 作者:行者123 更新时间:2023-12-05 01:22:35 25 4
gpt4 key购买 nike

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

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

enter image description here

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

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

enter image description here

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

  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)

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

我的查询似乎过于复杂了。

最佳答案

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
<表类="s-表"><头>托管结果<正文>123两者124就一个125就一个126就两个

Fiddle

关于sql - 尝试编写查询以指定客户是否完成了特定列的两种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73666620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com