执行多个WHERE语句的一个大查询

时间:2013-08-06 20:45:31

标签: sql where

我列出了116种不同的Agent到Vertex / Geo的组合,我必须确保它们配对在一起。例如,这里是我116列表中的一小部分。

AGNT    Vertex/Geo
5040    440292570
2010    440390000
1010    440390060
1180    440390246
1800    440390570
1130    440391110
1830    440391680
1410    440395020
1060    440397460
2000    440399685
1460    440399687
2020    440710000
1030    440710210

我一直在使用此查询来逐个检查每对。换句话说,我必须不断更改agnt_hse和VRTX_GEOCODE_HSE来检查每一对是否正确。

USE ExternalUser

SELECT  distinct HSE_KEY_HSE AS HOUSE_KEY, AGNT_HSE AS AGENT, VRTX_GEOCODE_HSE as GEOCODE

FROM        ExternalUser.Vantage.HSE_BASE 
      INNER JOIN externaluser.Vantage.HSL_LOB ON HSE_KEY_HSE = HSE_KEY_HSL 
      LEFT JOIN externaluser.Vantage.HSM_MEMO ON HSE_KEY_HSE = HSE_KEY_HSM

WHERE MEMO_NO_HSM = 1 
And sys_hsl = '8777' 
And sys_hsm = '8777'
And delivery_segment_id_hsl = 'C' 
And agnt_hse in ('5040') and VRTX_GEOCODE_HSE != '440292570'

有没有办法一次运行多个查询?

我熟悉UNION命令,但觉得可能有一种方法可以压缩编码,因为如果我被迫使用UNION命令,我会将大量查询粘贴到100x以上。

我在想

WHERE MEMO_NO_HSM = 1 
And sys_hsl = '8777' 
And sys_hsm = '8777'
And delivery_segment_id_hsl = 'C' 
And agnt_hse in ('5040') and VRTX_GEOCODE_HSE != '440292570' 
Then agnt_hse in ('2010') and VRTX_GEOCODE_HSE != '440390000' 
Then agnt_hse in ('1010') and VRTX_GEOCODE_HSE != '440390060' 
...etc

也许我说这一切都错了,运行查询的方式不同? 任何信息都非常感谢。

2 个答案:

答案 0 :(得分:0)

看起来您正试图获得您提供的列表的例外情况。也就是说,所有与代理匹配但具有不同顶点的行。

我会使用列表的显式辅助表(如果可能)来表达此查询,或使用CTE构造一个。这是CTE版本:

with pairs as (
      select '5040' as agent, '440292570' as vertex union all
      select '2010', '440390000'
      . . .
     )
SELECT distinct HSE_KEY_HSE AS HOUSE_KEY, AGNT_HSE AS AGENT, VRTX_GEOCODE_HSE as GEOCODE
FROM  ExternalUser.Vantage.HSE_BASE INNER JOIN
      externaluser.Vantage.HSL_LOB
      ON HSE_KEY_HSE = HSE_KEY_HSL LEFT JOIN 
      externaluser.Vantage.HSM_MEMO
      ON HSE_KEY_HSE = HSE_KEY_HSM join
      pairs p
      on p.agent = agnt_hse
WHERE MEMO_NO_HSM = 1 And
      sys_hsl = '8777' And
      sys_hsm = '8777' And
      delivery_segment_id_hsl = 'C' and
      (p.Vertex <> VRTX_GEOCODE_HSE)

答案 1 :(得分:0)

你没有指定你的rbdms,所以我将给出一个通用的例子。该原则应该适用于大多数数据库引擎,但您可能必须更改语法。我也假设agnt_hse和vertx_geocode_hse是整数。如果这个假设是错误的,那么所需的改变应该是显而易见的。

select yourfields
from yourtables
where concat(to_char(agnt_hse), to_char(vertx_geocode_hse)) in
(select concat(to_char(agnt_hse), to_char(vertx_geocode_hse))
from TheTablesYouAreLookingAt
minus 
select concat(to_char(agnt_hse), to_char(vertx_geocode_hse))
from TheTablesWithTheCorrectData)