我有以下两个表:
Table "Center":
CenterKey CenterName
--------- -----------
Center1 CenterName1
Center2 CenterName2
Center3 CenterName3
Center4 CenterName4
Center5 CenterName5
Center6 CenterName6
Center7 CenterName7
Center8 CenterName8
Table "Log":
CenterKey Date Value
--------- -------- -----
Center1 6/1/2014 10
Center2 6/3/2014 20
Center1 7/2/2014 30
Center3 7/3/2014 40
Center4 7/5/2014 50
Center5 7/8/2014 60
Center6 8/3/2014 70
我有兴趣创建一个视图,比如说“MyView”,如果我指定一个日期范围,它将返回其CenterKey不在日期范围内的CenterNames。
例如,如果我这样做
SELECT CenterName FROM MyView WHERE Date>='6/1/2014' AND Date <='6/30/2014'
我想要这个结果:
CenterName
----------
CenterName3
CenterName4
CenterName5
CenterName6
CenterName7
CenterName8
如果我这样做
SELECT CenterName FROM MyView WHERE Date>='7/1/2014' AND Date <='7/31/2014'
我想要这个结果:
CenterName
----------
CenterName2
CenterName6
CenterName7
CenterName8
如果我这样做
SELECT CenterName FROM MyView WHERE Date>='6/3/2014' AND Date <='7/5/2014'
我想要这个结果:
CenterName5
CenterName6
CenterName7
CenterName8
有人可以帮我创建MyView吗?
答案 0 :(得分:1)
以下查询应该执行您想要的操作:
select c.centername
from center c left outer join
log l
on l.centerkey = c.centerkey
group by c.centername
having sum(l.Date >='2014-07-01' AND .Date <='2014-07-31') = 0;
我无法想出一种方法可以轻松地将其合并到带有where
子句的视图中。
替代配方并没有真正帮助:
select c.centername
from center c
where not exists (select 1
from log l
where l.centerkey = c.centerkey and
l.Date >= '2014-07-01' AND l.Date <='2014-07-31'
);
编辑:
如果您有日历表,则可以执行以下操作:
select c.centername, ca.dte
from calendar ca cross join
center c left outer join
log l
on l.centerkey = c.centerkey and ca.dte = l.date
where l.date is null;
如果您将其放在带有where
的视图中,则当中心可用时,您将获得该范围内每个日期的单独行。
答案 1 :(得分:1)
SELECT CenterName
FROM Center
WHERE CenterKey NOT IN
( SELECT CenterKey
FROM Log
WHERE Date>='6/1/2014' AND Date <='6/30/2014'
)
答案 2 :(得分:1)
您只需加入表格:
SELECT Centername FROM Center AS c NATURAL JOIN Log as L WHERE Date>='6/3/2014' AND Date <='7/5/2014'
答案 3 :(得分:1)
最终SQL查询(http://sqlfiddle.com/#!2/570cb8/1):
SELECT *
FROM
(SELECT @startd:='2014-6-1', @endd:='2014-6-30') p , MyView;
查看功能:
create function startd() returns DATE DETERMINISTIC NO SQL return @startd;
create function endd() returns DATE DETERMINISTIC NO SQL return @endd;
create view MyView as
select centername from center c where not exists
(
select 1 from log l where l.centerkey = c.centerkey AND
d between startd() AND endd()
);
<强>参考强>