0

我在 MySQL 中有 sql 查询:

SELECT
   distinct 
   us.user_id as user_id, 
   us.ab_id,
   users.name,
   users.role,
   users.is_admin,
   DATE_FORMAT('2013-11-05T10:06:21+04:00', '%Y-%m') as month_m
FROM attach_offices as us
LEFT JOIN users ON users.id = user_id
WHERE us.`ab_id` = 999999999 and
 DATE_FORMAT('2013-11-05T10:06:21+04:00', '%Y-%m') between DATE_FORMAT(dt_begin, '%Y-%m') and DATE_FORMAT(`dt_end`, '%Y-%m')

如何将其转换为 Oracle 11g?我写这样的东西:

SELECT 
     distinct 
   attach_offices.user_id as user_id, 
   attach_offices.ab_id,
   users.name,
   users.role,
   users.is_admin,
   to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM') as month_m       
FROM attach_offices 
LEFT JOIN users ON users.id = user_id
WHERE attach_offices.ab_id = 999999999 and
 to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM') between to_date(to_char(dt_begin, 'YYYY-MM'), 'YYYY-MM') and to_date(to_char(dt_end, 'YYYY-MM'), 'YYYY-MM')

但它不起作用。日期的问题,当我使用2013-11-05T10:06:21+04:00它时它不起作用但是当我使用2013-11它时它是工作的

4

2 回答 2

1

因为TO_DATE将转换给定STRINGDATE格式,你已经指定了。
DATE_FORMAT但是按指定格式格式化 DATE。

因此,您有以下选择:
1. 如果您想获得DATE一些特别制作的所需STRING,那么您选择TO_CHAR(DATE, '<format>')
2. 如果您想转换STRINGDATE,您选择TO_DATE(string,'<format that describes string>')
3. 如果你需要一种特殊STRING的重新格式化作为另一种STRING,那么你两个都做。首先将其转换为日期,如2中所述,然后转换回字符串,如1中所述,使用所需的格式。
4.还有一种情况——如果你想改变输出格式,那么你需要ALTER SESSION变量NLS_DATE_FORMAT。

于 2013-11-05T06:59:33.370 回答
-1

我正在做这样的事情,但它似乎不是 DRY 和代码气味:

SELECT 
   distinct 
   attach_offices.user_id as user_id, 
   attach_offices.ab_id,
   users.name,
   users.role,
   users.is_admin,
   to_date(to_char(to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM-DD"T"HH24:MI:SS"+04:00"'), 'YYYY-MM'),'YYYY-MM') as month_m         
FROM attach_offices 
LEFT JOIN users ON users.id = user_id
WHERE attach_offices.ab_id = 999999999 and
to_date(to_char(to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM-DD"T"HH24:MI:SS"+04:00"'), 'YYYY-MM'),'YYYY-MM') between to_date(to_char(dt_begin, 'YYYY-MM'), 'YYYY-MM') and to_date(to_char(dt_end, 'YYYY-MM'), 'YYYY-MM')
于 2013-11-05T07:07:39.707 回答