Oracle:如何通过比较两个日期和另一个列来选择计数(2个值)

时间:2015-12-28 12:53:57

标签: sql oracle

我是甲骨文的新手。我有一个问题,我不知道如何查询。 我有如下虚拟数据。

CustID        Date        Value
==============================
  1         28/04/15        A
  1         21/12/15        B
  2         01/09/15        A
  2         17/08/15        B
  3         10/12/15        B
  4         09/07/15        A
  4         25/12/15        B

我想选择count(不同的CustID),其中Date大于30天,Value = A.然后,如果任何CustID与条件1匹配,则继续检查,如果Date小于30天且Value = B. / p>

这是我尝试过的查询。

Select Count(distinct CustID) From Table 
where Date < Sysdate -30 and Value = 'A'
Intersect
Select Count(distinct CustID)
From Table
where Date >= Sysdate -30 and Value = 'B';

我想要的查询输出应该如下所示。

Count(CustID)
2

在输出中,返回CustID = 1和CustID = 4,因为当日期超过30天时它们具有值A,而当日期少于30天时,它们具有值B.

请指导并帮助我查询如何查询。谢谢你的时间。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要满足两个条件的客户ID计数:

  • Date > Sysdate - 30 and Value = 'A'
  • Date <= Sysdate - 30 and Value = 'B'

如果是这样,这里有一种方法:

select count(*)
from (select custid
      from table t
      where (Date > Sysdate - 30 and Value = 'A') or
            (Date <= Sysdate - 30 and Value = 'B')
      group by custid
      having count(distinct value) = 2
     ) t

答案 1 :(得分:0)

这就是你想要的。我交换条件以符合您的要求。另外,请不要使用valuedate作为列名,因为这些是oracle保留关键字。我也改变了它们。

select count(*) from 
(
    Select distinct CustID 
    From Table1 
    where to_date(Date1,'DD/MM/RR') <= Sysdate -30 and Value1 = 'A'
        Intersect
    Select distinct CustID
    From Table1
    where to_date(Date1,'DD/MM/RR') > Sysdate -30 and Value1 = 'B'
)

在此处查看演示

http://sqlfiddle.com/#!4/7c7568/9

答案 2 :(得分:0)

使用存在且不存在对我来说似乎很清楚,并检查条件是否得到严格遵守:

select count (distinct cust_id) from TABLE1 where 
exists (select 1 from table1 t1a where t1a.N_DATE < (sysdate - 30) AND t1a.VAL = 'A' AND t1a.CUST_ID =  TABLE1.cust_id )
and not exists (select 1 from table1 t1b where t1b.N_DATE > (sysdate - 30) AND t1b.VAL = 'A' AND t1b.CUST_ID =  TABLE1.cust_id )
and exists (select 1 from table1 t1c where  t1c.VAL = 'B' AND t1c.CUST_ID =  TABLE1.cust_id AND t1c.N_DATE > (sysdate - 30)  ) 
and not exists (select 1 from table1 t1d where t1d.N_DATE < (sysdate - 30) AND t1d.VAL = 'B' AND t1d.CUST_ID =  TABLE1.cust_id)
;

我改变了表格和列的名称以避免混淆。