如何将 select 与变量一起使用

How to use select with a variable

为了简化,我有一个 table,我只想用蓝色的数据制作一个 select,这对我来说很棘手,因为我必须使用 where textanswer='dimibilli d2',但我会只得到记录 5、7、10、12 但我想得到 6、8、9 到

我该怎么做?

您似乎想要:

select t.*
from t
where t.tansdocnumber in (select t2.transdocnumber from t t2 where t2.textanswer = 'Dimobili D2);

select 行具有所需的文本列并匹配相应的 ID 以获得所需的输出。

declare @table table (transdocnumber int, textanswer varchar(20))
insert @table (transdocnumber,textanswer)
select 4631, 'Dimibilli D4' union all
select 4631, '' union all
select 5055, 'Dimibilli D2' union all
select 5055, '' union all
select 5270, 'Dimibilli D2' union all 
select 5270, '' union all 
select 5270, '' union all 
select 5513, 'Dimibilli D2' union all 
select 6279, 'Dimibilli D4' union all 
select 6616, 'Dimibilli D2' union all 
select 6773, 'Dimibilli D4' 

select t.transdocnumber,t.textanswer from (
select transdocnumber from @table where textanswer = 'Dimibilli D2' ) x
inner join @table t on x.transdocnumber = t.transdocnumber where t.textanswer = ''
union all
select transdocnumber,textanswer from @table where textanswer = 'Dimibilli D2'
order by transdocnumber

解决方案:

SELECT t.transdocnumber, t.extrafield_id, t.textanswer, t.BooleanAnswer, t.DtAlt
FROM (
    SELECT *
    FROM TABLE
    WHERE textanswer = 'Dimibilli D2'
    ) x
INNER JOIN TABLE t ON x.transdocnumber = t.transdocnumber
WHERE t.textanswer = ''

UNION ALL

SELECT transdocnumber, extrafield_id, textanswer, BooleanAnswer, DtAlt
FROM TABLE
WHERE textanswer = 'Dimibilli D2'
ORDER BY transdocnumber
select * from table
where textanswer not in ('dimobilli d4')

根据我的理解,您想要取回包含 textanswer='dimibilli d2' 和 textanswer='dimibilli d2' 的行,而不是第 4 行。

你不能用这种方式做到这一点,你应该以某种方式区分你想要的行。

使用

select * from table where (textanswer='dimibilli d2' or textanswer = '')

正如 Ven 建议的那样,结果是第 4、5、6、7、8、9、10、12 行,但你似乎只想要 5、6、7、8、9、10、12

例如你可以使用:

select * from table where (textanswer='dimibilli d2' or textanswer = '') and TransDocNumber>5000;

这应该有效

尝试使用以下查询:

select * from table
where (TextAnswer='Dimobili D2' or BooleanAnswer = '1') and TextAnswer!=''