簡體   English   中英

SQL查詢where子句以進行報告

[英]SQL query where clause for reporting

假設我的這張表包含以下數據:

Service_ID  Cust_ID  Service_Date   Next_Service_Date
-----------------------------------------------------
1            15      2016-01-1      2016-01-31
2            21      2016-01-1      2016-01-31
3            15      2016-01-31     2016-03-1

我需要一個條件來檢查是否在Service_Date為每個客戶而非整個表找到了Next_Service_Date

例如,id為15且Service_ID = 3 ,您可以看到Service_DateService_Date年1月31日簽訂

Service_ID = 1Next_Service_Date相同

所以查詢的輸出應該是

Service_ID  Cust_ID  Service_Date   Next_Service_Date
------------------------------------------------------
2            21      2016-01-1      2016-01-31

我希望我把一切都弄清楚了。

請注意為什么我要顯示記錄2,因為該客戶在Service_Date中沒有與Next_Service_Date中的日期匹配的記錄

如果我理解正確,那么您not exists希望not exists

select bt.*
from belowtable bt
where not exists (select 1
                  from belowtable bt2
                  where bt2.cust_id = bt.cust_id and
                        (bt2.next_service_date = bt.service_date or
                         bt2.service_date = bt.next_serice_date
                        )
                 );

編輯-我想我現在已經理解了您的問題-您想查找所有應該安排下一個服務日期的記錄,但是沒有? 如果是這樣,則可以將半聯接和反聯接結合使用。

如果我做不到,請告訴我我誤解的地方。

select
  t1.*
from
  MyTable t1
where exists (
  select null
  from MyTable t2
  where
    t1.Next_Service_Date = t2.Service_Date
)
and not exists (
  select null
  from MyTable t2
  where
    t1.Cust_Id = t2.Cust_Id and
    t1.Next_Service_Date = t2.Service_Date
)

暫無
暫無

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

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