如果在where子句中,则获取END AS列的值

时间:2018-08-23 10:53:04

标签: sql sql-server tsql

我有一个查询,我在KNOWN_AS列中使用case时说明其null,然后为'null',否则为'not null',以known_as2结尾。现在在where子句中,我要带仅包含'Not null'的行。

SELECT i.individual_ref, 0, 'KNOWNAS', i.FORENAMES, i.KNOWN_AS,
       case when KNOWN_AS is null then 'Null'  else ' Not null' end as known_as
FROM TestDatabase.dbo.INDIVIDUAL I
JOIN TestDatabase.dbo.MEMBER M ON M.INDIVIDUAL_REF=I.INDIVIDUAL_REF
WHERE  m.member_status IN(33,1316) 
  AND i.KNOWN_AS IS null or i.KNOWN_AS=''
  and m.MEMBER_STATUS in (33,1316)
  and LEN(i.FORENAMES) > '1' and i.FORENAMES !=''
  AND i.FORENAMES IS NOT NULL 

我想要帮助的原因是:-

我有一个表,其中包含名字,姓氏和known_as字段。 我想获取谁的known_as字段为空白/空,并且前额不为空或空白,并且前额长度为> 1的成员。我怎样才能做到这一点。成员状态来自另一个表调用成员,我要的成员处于活动和挂起状态,因此我说WHERE m.member_status IN(33,1316)。请采取任何解决方案。

最后我已经使用

解决了
 SELECT i.individual_ref,0,'KNOWNAS',
case when KNOWN_AS is null then 'Null'  else ' Not null' end as knownas2
FROM TestDatabase.dbo.INDIVIDUAL I
JOIN TestDatabase.dbo.MEMBER M ON M.INDIVIDUAL_REF=I.INDIVIDUAL_REF
       WHERE  m.member_status IN(33,1316) 
       and len(i.forenames)>2 and
          (IsNull(i.forenames, '') <> '') and (i.known_as is null or i.known_as='')

我不得不取len(i.forenames,'')> 2而不是1,因为有些成员的姓氏被错误地更新为Mr。

3 个答案:

答案 0 :(得分:1)

  

现在在where子句中,我要带只包含'Not null'的行。

只需将WHERE的{​​{1}}子句修改为:

IS NOT NULL

注意:

  • SELECT i.individual_ref, 0, 'KNOWNAS', i.FORENAMES, i.KNOWN_AS FROM DiTestDatabase.dbo.INDIVIDUAL I JOIN DiTestDatabase.dbo.MEMBER M ON M.INDIVIDUAL_REF = I.INDIVIDUAL_REF WHERE m.member_status IN (33,1316) AND LEN(i.FORENAMES) > 1 AND i.FORENAMES != '' AND i.FORENAMES IS NOT NULL AND i.KNOWN_AS IS NOT NULL; 将返回LEN()类型。因此,您无需使用INT

答案 1 :(得分:0)

可能会在下面的查询中为您提供帮助。

SELECT i.individual_ref, 0, 'KNOWNAS', i.FORENAMES, i.KNOWN_AS
,CASE WHEN i.KNOWN_AS IS NULL THEN 'null'
      ELSE 'Not null' END AS KNOWN_AS2
FROM DiTestDatabase.dbo.INDIVIDUAL I JOIN 
     DiTestDatabase.dbo.MEMBER M 
     ON M.INDIVIDUAL_REF = I.INDIVIDUAL_REF
WHERE m.member_status IN (33,1316) AND
      LEN(i.FORENAMES) > 1 AND i.FORENAMES != '' AND 
      i.FORENAMES IS NOT NULL AND i.KNOWN_AS IS NOT NULL;

答案 2 :(得分:0)

这样我们可以找到解决方案

SELECT * FROM ( SELECT i.individual_ref, 0, 'KNOWNAS', i.FORENAMES, i.KNOWN_AS, case when KNOWN_AS is null then 'Null' else 'Not null' end as known_as FROM DiTestDatabase.dbo.INDIVIDUAL I JOIN DiTestDatabase.dbo.MEMBER M ON M.INDIVIDUAL_REF=I.INDIVIDUAL_REF WHERE m.member_status IN(33,1316) AND i.KNOWN_AS IS null or i.KNOWN_AS='' and m.MEMBER_STATUS in (33,1316) and LEN(i.FORENAMES) > 1 and i.FORENAMES !='' AND i.FORENAMES IS NOT NULL) t WHERE t.known_as='Not null'