我有一个客户账单日表,看起来像这样:
CREATE TABLE customer_billing (
customer_name VARCHAR(20)
,bill_day INT
)
使用
等数据'ABC', 1
'DEF', 10
'GHI', 28
'JKL', 29
'MNO', 30
'PQR', 31
我每天都要向账单日等于当天的所有客户发送账单[即WHERE BILL_DAY = EXTRACT(DAY FROM SYSDATE)
]。
但是,如果客户的账单日是31,但今天是一个月的最后一天,只包含28天,29天或30天,我今天也想向该客户发送账单。
这是我到目前为止所拥有的。逻辑有效,但我认为有更好的方法来实现它。
SELECT customer_name
FROM customer_billing
WHERE 1 = 1
AND bill_day = (CASE
WHEN bill_day <= EXTRACT(DAY FROM LAST_DAY(SYSDATE))
THEN EXTRACT(DAY from SYSDATE)
WHEN EXTRACT(DAY from SYSDATE) = EXTRACT(DAY FROM LAST_DAY(SYSDATE))
AND bill_day > EXTRACT(DAY FROM LAST_DAY(SYSDATE))
THEN bill_day
END);
有更优雅的解决方案吗?
答案 0 :(得分:4)
稍微简洁的版本:
SELECT customer_name
FROM customer_billing
WHERE LEAST(bill_day, EXTRACT(DAY FROM LAST_DAY(SYSDATE)))
= EXTRACT(DAY FROM SYSDATE);
答案 1 :(得分:2)
我在想:
bill_day = EXTRACT(DAY FROM SYSDATE)
OR
(
EXTRACT(DAY FROM SYSDATE) = EXTRACT(DAY FROM LAST_DAY(SYSDATE))
AND
bill_day > EXTRACT(DAY FROM LAST_DAY(SYSDATE))
)