id key value code
1 starttime 20140822 8
2 starttime 20140922 9
3 endtime 20140925 9
4 type ok 9
5 endtime 20140830 8
6 type ok 8
表结构如上
想通过一sql查询
key=starttime 且 value<20140823
key=endtime 且 value>20140823
key=type且 value=ok
的code值
------解决方案--------------------
select * from T
where (key='starttime' and value<'20140823')
or (key='endtime' and value>'20140823')
or (key='type' and value='ok')
------解决方案--------------------
with t as
(select 1 id, 'starttime' key, '20140822' value, 8 code
from dual
union all
select 2 id, 'starttime' key, '20140922' value, 9 code
from dual
union all
select 3 id, 'endtime' key, '20140925' value, 9 code
from dual
union all
select 4 id, 'type' key, 'ok' value, 9 code
from dual
union all
select 5 id, 'endtime' key, '20140830' value, 8 code
from dual
union all
select 6 id, 'type' key, 'ok' value, 8 code
from dual)
select distinct code
from t
where t.code not in
(select distinct code
from t
where (key = 'starttime' and value >= '20140823')
or (key = 'endtime' and value <= '20140823')
or (key = 'type' and value <> 'ok'));
------解决方案--------------------
--测试数据
WITH t AS
(SELECT 1 id, 'starttime' key, '20140822' VALUE, 8 code
FROM dual
UNION ALL
SELECT 2 id, 'starttime' key, '20140922' VALUE, 9 code
FROM dual
UNION ALL
SELECT 3 id, 'endtime' key, '20140925' VALUE, 9 code
FROM dual
UNION ALL
SELECT 4 id, 'type' key, 'ok' VALUE, 9 code
FROM dual
UNION ALL
SELECT 5 id, 'endtime' key, '20140830' VALUE, 8 code
FROM dual
UNION ALL
SELECT 6 id, 'type' key, 'ok' VALUE, 8 code
FROM dual
UNION ALL
SELECT 7 id, 'type' key, 's' VALUE, 8 code
FROM dual)
--查询语句
SELECT m.*, n.value
FROM (SELECT code,
MIN(decode(key, 'starttime', VALUE, NULL)) starttime,
MAX(decode(key, 'endtime', VALUE, NULL)) endtime
FROM t
GROUP BY code) m
LEFT JOIN (SELECT code, VALUE
FROM t
WHERE key = 'type') n
ON m.code = n.code
--结果
CODE STARTTIME ENDTIME VALUE
---------- --------- -------- --------
9 20140922 20140925 ok