简体   繁体   中英

SQL Querying a slowly changing dimension

I have a table with Staion Platforms and when they were operational and when they were closed. I want to get the count of stations that were operational between 01/01/2010 and 31/01/2010 On the right side is the result Im looking for. I've highlighted in Yellow those that should not be included in the result. The stations need to be grouped by Location. MAP_id is the PK.

The way I think it should work is to go to each row and check whether the start and end dates fall within Jan 2010.

Can this Query work?

SELECT ...
FROM ...
WHERE
'2010/01/31' between startdate and 
case when enddate is null then Getdate()
else enddate
end

Any help would be appriciated.

在此处输入图片说明

Your condition is: "operational between 01/01/2010 and 31/01/2010". I would expect to see both these dates in the query.

This is an example of an overlapping time-intervals problem. What this is saying is that the station started on or before 01/01/2010 and ended on or after 31/01/2010. Here is the where clause for that logic:

where startdate <= '2010-01-01' and
      (enddate is null or enddate >= '2010-01-31');

Note that the logic might be slightly different, depending on whether the end points are included or not.

You can also write this as:

where startdate <= '2010-01-01' and
      coalesce(enddate, getdate()) >= '2010-01-31');

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