我有一个问题,我必须从商店表中查找商店的详细信息,该商品表会在周末打开最新商品。在商店表中,我有一个名为weekendHours的属性,其类型为varchar2,示例为:(上午10:00 - 下午5:00)。 我试过了 To_char(S.WeekendHours = max(S.WeekendHours); 但它不起作用!! 我怎么能这样做?
答案 0 :(得分:1)
如果您想要打开最新的商店,那么您可以想到:
select t.*
from t
order by t.weekendhours desc
fetch first 1 row only;
但是,使用您的时间格式,这将无效,因为凌晨2点将在下午1点之后。
因此,您需要将范围转换为时间。这是一种方法:
select t.*
from t
order by cast(substring(t.weekendhours, 1, 8) as time) desc
fetch first 1 row only;
当然,这些查询在许多数据库中使用通用方法。逻辑可能适用于您的数据库,但语法可能不同。
注意:所有这一切都是因为列weekendhours
已损坏。它应该分为两列,weekend_opentime
和weekend_closetime
。然后查询将是微不足道的。
答案 1 :(得分:0)
您可以使用正则表达式提取开始和结束时间,然后根据需要对其进行操作:
SELECT s.*,
TRIM(REGEXP_SUBSTR(s.weekend_hours, '[0-9]+:*[0-9]* *(am|pm)*', 1, 1)) AS OPENING_HOUR_STRING,
TRIM(REGEXP_SUBSTR(s.weekend_hours, '[0-9]+:*[0-9]* *(am|pm)*', 1, 2)) AS CLOSING_HOUR_STRING
FROM STORE s
获得上述基本信息后,您可以对其进行操作以获得日期的开始和结束时间,然后在相应的字段上使用MAX:
WITH cteSTORE_STRING_VALUES AS
(SELECT s.*,
TRIM(REGEXP_SUBSTR(s.weekend_hours, '[0-9]+:*[0-9]* *(am|pm)*', 1, 1)) AS OPENING_HOUR_STRING,
TRIM(REGEXP_SUBSTR(s.weekend_hours, '[0-9]+:*[0-9]* *(am|pm)*', 1, 2)) AS CLOSING_HOUR_STRING
FROM STORE s),
cteALL_STORE_VALUES AS
(SELECT s.*,
CASE
WHEN LENGTH(OPENING_HOUR_STRING) < 4 THEN LPAD(OPENING_HOUR_STRING, 4, '0')
ELSE OPENING_HOUR_STRING
END AS PADDED_OPENING_STRING,
CASE
WHEN LENGTH(CLOSING_HOUR_STRING) < 4 THEN LPAD(CLOSING_HOUR_STRING, 4, '0')
ELSE CLOSING_HOUR_STRING
END AS PADDED_CLOSING_STRING
FROM cteSTORE_STRING_VALUES s),
cteSTORES_WITH_HOURS AS
(SELECT a.*,
CASE
WHEN UPPER(SUBSTR(a.OPENING_HOUR_STRING, -3)) IN (' AM', ' PM') THEN
TO_DATE(a.OPENING_HOUR_STRING, 'HH:MI AM')
WHEN UPPER(SUBSTR(a.OPENING_HOUR_STRING, -2)) IN ('AM', 'PM') THEN
TO_DATE(a.OPENING_HOUR_STRING, 'HH:MIAM')
WHEN INSTR(a.OPENING_HOUR_STRING, ':') > 0 THEN
TO_DATE(a.OPENING_HOUR_STRING, 'HH24:MI')
ELSE
TO_DATE(a.PADDED_OPENING_STRING, 'HH24MI')
END AS OPENING_HOURS,
CASE
WHEN UPPER(SUBSTR(a.CLOSING_HOUR_STRING, -3)) IN (' AM', ' PM') THEN
TO_DATE(a.CLOSING_HOUR_STRING, 'HH:MI AM')
WHEN UPPER(SUBSTR(a.CLOSING_HOUR_STRING, -2)) IN ('AM', 'PM') THEN
TO_DATE(a.CLOSING_HOUR_STRING, 'HH:MIAM')
WHEN INSTR(a.CLOSING_HOUR_STRING, ':') > 0 THEN
TO_DATE(a.CLOSING_HOUR_STRING, 'HH24:MI')
ELSE
TO_DATE(a.PADDED_CLOSING_STRING, 'HH24MI')
END AS CLOSING_HOURS
FROM cteALL_STORE_VALUES a)
SELECT *
FROM cteSTORES_WITH_HOURS
WHERE OPENING_HOURS = (SELECT MAX(OPENING_HOURS)
FROM cteSTORES_WITH_HOURS);
祝你好运。