我需要有关SQL代码的帮助。
我有一个看起来像这样的表:
acIdent acSubject acCode
201.2.013 Jusel F-203
201.2.013 Tehnomehanika F-101 (1,5 mm)
我有一个基于某些过滤器创建报告的应用程序。
这就是我要达到的目标:
当我选择acSubject'Tehnomehanika'时,然后返回'F-101(1.5 mm)' 当我将其保留为空白时,它将是”,然后返回前1个acCode-'F-203'
它只能返回一条记录
我尝试了类似的方法,但是它不起作用:
declare @acSubject char(30)
set @acSubject = ''
select
case
when acSubject = @acSubject then (select acCode from tHE_SetItemExtItemSubj where acSubject = @acSubject and acIdent = '201.2.013')
else (select top 1 acCode from tHE_SetItemExtItemSubj where acIdent = '201.2.013')
end
from tHE_SetItemExtItemSubj
where acIdent = '201.2.013'
and acSubject = @acSubject
答案 0 :(得分:2)
当我将其留空表示它是null
还是''
?
要涵盖这两种情况,可以使用coalesce()
:
select
case
when coalesce(rtrim(ltrim(@acSubject)), '') <> '' then (
select acCode from tHE_SetItemExtItemSubj
where acSubject = @acSubject and acIdent = '201.2.013'
)
else (
select top 1 acCode from tHE_SetItemExtItemSubj
where acIdent = '201.2.013'
)
end acCode
如果列acSubject
是唯一的并且第一种情况查询仅返回1行,这将起作用,否则,您也必须使用它top 1
。
编写上述逻辑的另一种方法是:
select top 1 acCode
from tHE_SetItemExtItemSubj
where
acIdent = '201.2.013'
and
(coalesce(rtrim(ltrim(@acSubject)), '') = '' or acSubject = @acSubject)
答案 1 :(得分:1)
这可以使用union
declare @acSubject char(30)
set @acSubject = ''
select acCode
from (select acCode from tHE_SetItemExtItemSubj where acSubject = @acSubject
union
select case when @acSubject = '' then (select top 1 acCode from tHE_SetItemExtItemSubj) end
)tbl
where acCode is not null