SQL Server:在多联接查询中按前3个单词和后3个单词搜索

时间:2019-06-27 17:13:11

标签: sql sql-server

我想编写一条SQL Server语句,该语句搜索以某些内容开头的字符串中的前3个单词以及后3个单词。

示例:19032560951039OHUG我想使用**HUG**作为搜索参数 也为400305我想使用400

我已经尝试过,但是它返回一个空查询。

首先:主要查询

select * 
from memtrans 
where right(trx_no, 3) = 'HUG' 
  and left(gl_no, 3)= '400'

主要查询的表

enter image description here

当我用主查询编写联接查询时:

select 
    custinfo.SavOfficer, 
   -sum(memtrans.amount) as feencharges
from  
    memtrans 
inner join
    custinfo on memtrans.ac_no = custinfo.cust_no
where
    right(memtrans.trx_no, 3) = 'HUG' 
    and left(memtrans.gl_no, 3)= '400'
group by
    custinfo.SavOfficer

哪个返回空结果。但是,如果我删除WHERE子句,结果将返回

select 
    custinfo.SavOfficer,
    -sum(memtrans.amount) as feencharges
from 
    memtrans 
inner join
    custinfo on memtrans.ac_no = custinfo.cust_no
group by 
    custinfo.SavOfficer

不带WHERE子句的查询表样本

enter image description here

custinfo

enter image description here

2 个答案:

答案 0 :(得分:1)

感谢大家的帮助。我的客户给了他一个未知的错误交易代码,他们更改了某些表结构,从而导致了不同的交易代码。深入研究它之后,我能够使用不同的代码提取结果。

先前的代码

select custinfo.SavOfficer,
  -SUM(memtrans.amount) AS feencharges
   FROM memtrans 
  INNER JOIN 
  custinfo
  ON  memtrans.ac_no = custinfo.cust_no
  WHERE
   right(memtrans.trx_no,3) = 'HUG' 
   AND left(memtrans.gl_no,3)= '400'
  GROUP BY custinfo.SavOfficer

新代码:

select custinfo.SavOfficer,
 -SUM(memtrans.amount) AS feencharges
 from memtrans 
inner join 
custinfo
on  memtrans.ac_no = custinfo.cust_no
where
 right(memtrans.trx_no,3) = 'HUG' or right(memtrans.trx_no,1) = 'N'

group by custinfo.SavOfficer

在此期间,我们非常感谢 @mgrollins @Larnu

答案 1 :(得分:0)

如果您同时寻找400和拥抱,则应该可以。

SELECT * 
FROM
memtrans
INNER JOIN 
custinfo
ON  memtrans.ac_no = custinfo.cust_no
WHERE RIGHT(trx_no, 3) = 'HUG'
AND LEFT(trx_no, 3) = '400'

如果您要查找400或拥抱,请使用它。

SELECT * 
FROM
memtrans
INNER JOIN 
custinfo
ON  memtrans.ac_no = custinfo.cust_no
WHERE RIGHT(trx_no, 3) = 'HUG' 
AND LEFT(trx_no, 3) = '400'