SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Question on flag
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

rajsqlteam
Starting Member

14 Posts

Posted - 12/17/2012 :  14:59:46  Show Profile  Reply with Quote
Hi,

I am trying to flag with '1' if two rows of same ID has NOT NULL value,
SOURCE TABLE:

ID LINE COL
1 1 'A'
1 2 'B'
2 1 NULL
1 1 NULL
3 1 'C'
3 4 'D'

Desired O/P:

ID Flag
1 1
2 0
3 1

I want to group by ID and flag if it has a not Null value. Please let me know thanks in advance.

bitsmed
Constraint Violating Yak Guru

323 Posts

Posted - 12/17/2012 :  15:48:26  Show Profile  Reply with Quote
try this:

select id
      ,sign(sum(case when col is null then 0 else 1 end)) as flag
  from thetable as a
 group by id
 order by id


edit:
the above does not work as intended, try this instead:

select id
      ,case when sum(case when col is null then 0 else 1 end)>2 then 1 else 0 end as flag
  from thetable as a
 group by id
 order by id


Edited by - bitsmed on 12/17/2012 15:56:12
Go to Top of Page

Bustaz Kool
Flowing Fount of Yak Knowledge

USA
1645 Posts

Posted - 12/18/2012 :  18:44:14  Show Profile  Reply with Quote
Slight variation:
select
  id,
  case when count(col) > 1 then 1 else 0 end flag
from
  @MyTbl
group by id
order by id;
The COUNT aggregate won't count NULL values. This potentially runs a little quicker.

=================================================
Hear the sledges with the bells - silver bells!
What a world of merriment their melody foretells!
Go to Top of Page

waterduck
Aged Yak Warrior

Malaysia
961 Posts

Posted - 12/18/2012 :  21:05:38  Show Profile  Reply with Quote
select ID, sum(distinct case when COL IS not null then 1 else 0 end)
from @MyTbl
group by id
Go to Top of Page

rajsqlteam
Starting Member

14 Posts

Posted - 12/19/2012 :  09:50:40  Show Profile  Reply with Quote
Thank you guys!
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000