这个条件需要子查询?

时间:2014-08-20 13:25:23

标签: sql-server

这个查询正在以我需要的格式正确地提取数据,但有一个条件我似乎无法突破...我只想拉出目录号(sCat)文本代码(stxttype)有一个' NEURPIC'以及相应的IDURPIC'必须满足这两个条件。所以说明stxttype IN(' NEURPIC',' IDURPIC')是行不通的,因为它会拉动任何一个或哪个目录号。基本上我需要消灭'NEURPIC'所以我需要确保目录编号同时具有“NEURPIC”和“#NEERPIC”。和' IDURPIC'。它几乎是一个错误编码的重复URL,这就是我需要删除的原因。一如既往地感谢您。

DECLARE @nIdPub int

SELECT  @nIdPub = 12439 

SELECT     'TX1.0P'                     AS [Record ID]
, ''                                    AS [Seller ID Qualifier]
, tbCo.nIdIdw                           AS [IDW Private ID]
, CONVERT(smalldatetime,getdate(), 112) AS [Time Stamp]
, 'C'                                   AS [Update Status]
, ISNULL(tbItem.sUpc, '')               AS [UPC]    
, ISNULL(tbItem.sGtin, '')              AS [GTIN]               
, ISNULL(tbItem.sEan, '')               AS [EAN]            
, tbItem.sCat                           AS [Catalog Number]
, tbItemTxt.sTxtType                    AS [Type Code]
, tbItemTxt.sTxt                        AS [Text]
, tbItemTxt.sLang                       AS [Language Code]

FROM        tbItemTxt INNER JOIN
        tbItem ON tbItemTxt.nItemId = tbItem.nItemId INNER JOIN
        tbCo ON tbItem.nIdPub = tbCo.nIdPub

WHERE       tbItem.nIdPub = @nIdPub
and tbItemTxt.sTxtType LIKE '%URPIC%'

ORDER by sCat

预期结果应如下......

sCat        sTxtType
11455        IDURPIC
11455        NEURPIC
22335        IDURPIC
22335        NEURPIC
45678        IDURPIC
45678        NEURPIC

2 个答案:

答案 0 :(得分:0)

好的,我认为你要找的是tbItem中的所有行都有一个sCat同时具有sTxtType =' NEURPIC'和sTxtType =' IDURPIC'。您可以通过使用以下内容替换WHERE子句来修改查询以返回这些查询。它基本上说这行的sCat是否有一行NEURPIC,并且它也有一行IDURPIC,但现有行都不需要是当前考虑的行。

WHERE tbItem.nIdPub = @nIdPub  
  AND EXISTS (SELECT * FROM tbItemTxt as NPIC WHERE NPIC.sCat = tbItem.sCat AND NPIC.sTxtType='NEURPIC')  
  AND EXISTS (SELECT * FROM tbItemTxt as IPIC WHERE IPIC.sCat = tbItem.sCat AND IPIC.sTxtType='IDURPIC')  

请注意,如果您的sTxtType值不是' IDURPIC'或者' NEURPIC'对于任何具有所需值的sCat,这也将返回这些,因此您可能希望添加类似原始的" stxttype IN(' NEURPIC',' IDURPIC&#39 ;)"

答案 1 :(得分:0)

尝试在两个条件下使用内部联接,例如:

SELECT    
    t.sTxtType  AS [TYPE Code]  , 
    t.sTxt    AS [TEXT]
FROM        
    tbItem i INNER JOIN
    tbCo c ON 
    i.nIdPub = c.nIdPub INNER JOIN
    (SELECT DISTINCT
        nItemId, sTxtType, sTxt
    FROM
        tbItemTxt
    WHERE
        sTxtType = 'IDURPIC') ti ON
    i.nItemId = ti.nItemId  INNER JOIN
    (SELECT DISTINCT
        nItemId, sTxtType, sTxt
    FROM
        tbItemTxt
    WHERE
        sTxtType = 'NEURPIC') tn ON
    ti.nitemid = tn.nitemid
WHERE       
    i.nIdPub = @nIdPub