简体   繁体   中英

Provide status of an Activity based on date column in a view in SQL Server

In the view have to provide Status based on date.

The condition is:

  • If one of the activities doesn't have a date for the person, then Status is Active

  • If all the activities have a date for the person, then Status is Not Active

How do I get STATUS for a person?

For example:

|PersonId|Name|Activity | Date      | 
+--------+----+---------+-----------+
| 1      |John| a       | 01/01/2015|
| 1      |John| b       | 03/12/2016|
| 1      |John| c       | 02/13/2017|
| 2      |Sam | d       | 06/01/2014|
| 2      |Sam | e       | 05/18/2016|
| 2      |Sam | f       | NULL      |   

Output in the view:

|PersonId|Name|Status    | 
+--------+----+----------+
| 1      |John|Not Active| 
| 2      |Sam | Active   | 

You can do this with aggregation:

select personid, name,
       (case when count(*) = count(date) then 'Not Active' else 'Active' end) as status
from t
group by personid, name;

I think Gordon's answer is better, but since I started typing this out, I figured i'd finish it anyway. something like

declare @maxDate date = datefromparts(9999, 12, 31)

select case when max(isnull(Date, @MaxDate)) = @maxDate) then 'Active' else 'inactive'
from ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM