[英]How to select rows where date is greater than the date in another row?
我有一張有客戶卡的桌子。 一個客戶可以擁有幾張卡。 每張客戶卡都有一行。 如果客戶有幾張卡,則有幾行。 有兩種不同的卡類型A和B。對於每張卡,將存儲last_used
日期。
我想檢查是否存在同時具有A 和 B類型客戶卡的客戶,其中卡B的最后使用日期比卡A的最后使用日期年輕。
這是我的表CUSTOMER_CARDS。
card_id | customer_id | card_type | last_used
----------------------------------------------
1 | c1 | A | 2017-07-07
2 | c1 | B | 2016-04-01
3 | c2 | A | 2017-06-04
4 | c2 | B | 2017-07-03
5 | c3 | A | 2016-02-23
6 | c3 | B | 2017-04-17
我需要一條選擇語句,該語句選擇客戶c2
的customer_id
,該customer_id
的B型卡比其A型卡年輕。我該如何實現?
您需要Group By
和Having
條款
select customer_id
from yourtable
Group by customer_id
Having Min(case when card_type = 'B' then last_used end) > Max(case when card_type = 'A' then last_used end)
你可以嘗試這樣的事情嗎?
SELECT A.card_id, A.customer_id, A.card_type, A.last_used
FROM CUSTOMER_CARDS A
INNER JOIN CUSTOMER_CARDS B ON A.customer_id=B.customer_id
WHERE A.card_type='B'
AND B.card_type='A' AND A.last_user > B.last_used
;
select d1.cusid,d1.cardtyp,d1.lstusd
from democat d1
join democat d2 on d1.cusid = d2.cusid
where d1.lstusd < d2.lstusd and d1.cardtyp = 'B'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.