确定在SQL Server中的select查询中返回特定行的where子句

时间:2017-11-26 16:16:10

标签: sql sql-server select subquery

我在SQL Server中使用select查询连接三个表来获取结果。

  1. 联络表
  2. Ticker Table
  3. 行业表
  4. 虽然联系人表包含单独的联系人记录,但其他两个表对每个联系人都有多个记录。基本上,它包含该人拥有的股票(如苹果,微软等)以及他感兴趣的行业。当我们发送搜索条件时,选择查询会为每个联系人返回一行,例如' Apple',& #39;卫生部门'现在,在返回的结果中,我想打印一列,其中包含有关匹配条件的信息。

    例如

    ----------------------------------------------------
    Contact id  name    email
    ----------------------------------------------------
        1       John    john@sas.com
        2       Bret    bret@sas.com
        3       Mike    mike@cityon.com
    
    Ticker  id  contact_id  Ticker
    ---------------------------------------------------
        1   1   APPLE
        2   1   MCSFT
        3   2   GOOGLE
        4   3   APPLE
    
    Sector  id  contact_id  Sector
    ---------------------------------------------------
        1   1   Health
        2   2   Retail
        3   2   FMCG
        4   3   FMCG
    

    查询是:

    select 
        id, name, email, reason
    from 
        contact
    where 
        id in (select ttemp.contact_id
               from ticker ttemp
               where ttemp.ticker in ('GOOGLE')) 
        or id in (select stemp.contact_id 
                  from sector stemp
                  where stemp.sector in ('FMCG'))
    

    现在它返回联系人2(Bret)和3(Mike)。我想打印GOOGLE,FMCG'对于Bret和' FMCG'对于迈克的原因列。

    希望我能清楚这一点。朋友有什么建议?

2 个答案:

答案 0 :(得分:0)

我想我会使用子查询:

select id, name, email, reason,
       stuff( coalesce(',' + ticker, '') + coalesce(',' + sector),
              1, 1, ''
            )
from (select c.*,
             (case when id in (select ttemp.contact_id
                               from ticker ttemp
                               where ttemp.ticker in ('GOOGLE')
                              )
                   then 'GOOGLE'
              end) as ticker,
             (case when id in (select stemp.contact_id 
                               from sector stemp
                               where stemp.sector in ('FMCG')
                              )
                   then 'FMCG'
              end) as sector
      from contact c
     ) c
where ticker is not null or sector is not null;

答案 1 :(得分:0)

这是使用LEFT JOIN执行此操作的一种方法。如果联系人没有左边连接的“GOOGLE”或“FMCG”,则两个字段都应为NULL。在WHERE中,我使用空格合并任何NULL,以查看连接是否导致空字符串。

SELECT C.Contact_id
      ,C.name
      ,C.email
      ,REPLACE(LTRIM(COALESCE(T.Ticker, '') + ' ' 
                   + COALESCE(S.Sector, '')
              ), ' ', ', ') AS Reason
  FROM contact C LEFT JOIN ticker T ON C.Contact_id = T.contact_id AND Ticker = 'GOOGLE'
                 LEFT JOIN sector S ON C.Contact_id = S.contact_id AND S.Sector = 'FMCG'
WHERE COALESCE(T.Ticker, '') + COALESCE(S.Sector, '') <> ''

生成输出:

Contact_id  name    email            Reason
2           Bret    bret@sas.com     GOOGLE, FMCG
3           Mike    mike@cityon.com  FMCG

http://sqlfiddle.com/#!6/40090/19/0