简体   繁体   中英

How to select rows where date is greater than the date in another row?

I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table 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 

I need a select statement which selects the customer_id of customer c2 , who has a card of type B which is younger then his cards of type A. How do I achieve this?

You need Group By and Having clause

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)

Can you try something like this?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM