एक पहेली के रूप में, इस अभ्यास में यह बुरी तरह अपने डेटा की प्रकृति पर निर्भर प्रदर्शन कर सकते हैं एक समाधान है ...। अपने अनुक्रमित देखो, किसी भी मामले में:
create database tmp;
create table t (value float, dt date); -- if you use int, you need to care about rounding
insert into t values (10, '2012-10-30'), (15, '2012-10-29'), (null, '2012-10-28'), (null, '2012-10-27'), (7, '2012-10-26');
select t1.dt, t1.value, t2.dt, t2.value, count(*) cnt
from t t1, t t2, t t3
where
t2.dt >= t1.dt and t2.value is not null
and not exists (
select *
from t
where t.dt < t2.dt and t.dt >= t1.dt and t.value is not null
)
and t3.dt <= t2.dt
and not exists (
select *
from t where t.dt >= t3.dt and t.dt < t2.dt and t.value is not null
)
group by t1.dt;
+------------+-------+------------+-------+-----+
| dt | value | dt | value | cnt |
+------------+-------+------------+-------+-----+
| 2012-10-26 | 7 | 2012-10-26 | 7 | 1 |
| 2012-10-27 | NULL | 2012-10-29 | 15 | 3 |
| 2012-10-28 | NULL | 2012-10-29 | 15 | 3 |
| 2012-10-29 | 15 | 2012-10-29 | 15 | 3 |
| 2012-10-30 | 10 | 2012-10-30 | 10 | 1 |
+------------+-------+------------+-------+-----+
5 rows in set (0.00 sec)
select dt, value/cnt
from (
select t1.dt , t2.value, count(*) cnt
from t t1, t t2, t t3
where
t2.dt >= t1.dt and t2.value is not null
and not exists (
select *
from t
where t.dt < t2.dt and t.dt >= t1.dt and t.value is not null
)
and t3.dt <= t2.dt
and not exists (
select *
from t
where t.dt >= t3.dt and t.dt < t2.dt and t.value is not null
)
group by t1.dt
) x;
+------------+-----------+
| dt | value/cnt |
+------------+-----------+
| 2012-10-26 | 7 |
| 2012-10-27 | 5 |
| 2012-10-28 | 5 |
| 2012-10-29 | 5 |
| 2012-10-30 | 10 |
+------------+-----------+
5 rows in set (0.00 sec)
स्पष्टीकरण:
- t1 मूल तालिका है
- t2 एक गैर शून्य मान
साथ कम से कम अधिक से अधिक की तारीख के साथ तालिका में पंक्ति है
- t3 के बीच में सभी पंक्तियों हैं, इसलिए हम दूसरों के द्वारा समूह और भरोसा कर सकते हैं
खेद है कि मैं स्पष्ट नहीं हो सकता। यह मेरे लिए बहुत भ्रामक :-)
+1 बहुत अच्छा सवाल है। और इसमें सब कुछ है जो इसकी ज़रूरत है - ठीक है, मैं पहेली से PostgreSQL 9.2 का अनुमान लगाता हूं। –