簡體   English   中英

Oracle:如何通過比較兩個日期和另一列(2個值)來選擇計數

[英]Oracle: How to select count by comparing two dates and another one column(2 values)

我是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(distinct CustID),其中Date大於30天,並且Value =A。然后,如果任何CustID與條件相匹配,則繼續檢查,如果Date小於30天且Value =B。

這是我嘗試過的查詢。

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。

請指導並幫助我如何查詢此內容。 感謝您的時間。

如果我理解正確,那么您希望統計滿足以下兩個條件的客戶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

這就是你想要的。 我調換了條件以符合您的要求。 另外,請不要使用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

對我來說,使用存在和不存在似乎很清楚,並檢查條件是否得到嚴格遵守:

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)
;

為了避免混淆,我更改了表和列的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM