我在查询mysql中遇到了问题 我想找到2日期除以日期之间的每个日期的小时数 例如,
我已经开始 14/12/2014 09:00:00 AM ,并且结束 17/12/2014 03:30:00 AM
我想这样结果
这可能在MySQL或Oracle SQL查询中吗?
答案 0 :(得分:0)
使用MySQL TIMESTAMPDIFF或Oracle EXTRACT函数计算Datetime类型(第2和第3个参数)的两个值字段之间的差异。传递的第一个参数是您选择的测量值来计算差异。这可能是HOUR,MINUTE,SECOND,DAY等。
SELECT
`startdate` AS `date`,
TIMESTAMPDIFF(
HOUR,
`startdate`,
`enddate`) AS `hours_delta`
FROM my_table
结果将是:
___ _______日期____ hours_delta
14/12/2014 ________ 66 ________
15/12/1014 ________..._________
答案 1 :(得分:0)
最后,我找到了oracle sql的查询...
感谢您的帮助
SELECT
TO_DATE (START_DATE + COLUMN_VALUE - 1, 'DD/MM/YYYY') AS THE_DATE,
CASE
WHEN TO_DATE (START_DATE, 'DD/MM/YYYY') = TO_DATE (END_DATE, 'DD/MM/YYYY')
THEN (END_DATE - START_DATE)*24
WHEN (START_DATE + COLUMN_VALUE - 1) = START_DATE
THEN (23 - TO_CHAR (START_DATE, 'HH24')) + ((60 - TO_CHAR (START_DATE, 'MI'))/60) + ((360 - TO_CHAR (START_DATE, 'SS'))/360)
WHEN TO_DATE (START_DATE + COLUMN_VALUE - 1, 'DD/MM/YYYY') <> TO_DATE (END_DATE, 'DD/MM/YYYY')
THEN 24
ELSE TO_CHAR (END_DATE, 'HH24') +
(TO_CHAR (END_DATE, 'MI')/60) +
(TO_CHAR (END_DATE, 'SS')/360) END
FROM MY_TABLE,
TABLE( CAST( MULTISET (
SELECT
LEVEL L
FROM DUAL
CONNECT BY LEVEL <= END_DATE - START_DATE + 1) AS SYS.ODCINUMBERLIST))
答案 2 :(得分:0)
Oracle 11g R2架构设置:
CREATE TABLE MY_TABLE ( ID, START_DATE, END_DATE ) AS
SELECT 1, TO_DATE( '14/12/2014 09:00:00AM', 'DD/MM/YYYY HH:MI:SSAM'), TO_DATE( '17/12/2014 03:30:00AM', 'DD/MM/YYYY HH:MI:SSAM') FROM DUAL
UNION ALL SELECT 2, TO_DATE( '20/12/2014 09:00:00AM', 'DD/MM/YYYY HH:MI:SSAM'), TO_DATE( '20/12/2014 03:30:00PM', 'DD/MM/YYYY HH:MI:SSAM') FROM DUAL
查询1 :
WITH Differences AS (
SELECT ID,
TRUNC( START_DATE ) AS Day,
LEAST(
TRUNC( START_DATE ) + INTERVAL '1' DAY,
END_DATE
) - START_DATE AS Diff
FROM MY_TABLE
UNION
SELECT ID,
COLUMN_VALUE,
CASE WHEN COLUMN_VALUE < TRUNC( END_DATE )
THEN 1
ELSE END_DATE - COLUMN_VALUE
END
FROM MY_TABLE,
TABLE( CAST( MULTISET (
SELECT TRUNC( START_DATE ) + LEVEL
FROM DUAL
WHERE TRUNC( START_DATE ) + LEVEL <= TRUNC( END_DATE )
CONNECT BY
TRUNC( START_DATE ) + LEVEL <= TRUNC( END_DATE )
) AS SYS.ODCIDATELIST ) )
)
SELECT ID,
TO_CHAR( Day, 'YYYY-MM-DD' ) AS Day,
TO_CHAR( TO_NUMBER( Diff * 24 ), '99D90' )
|| ' hour ' AS Hours
FROM DIFFERENCES
<强> Results 强>:
| ID | DAY | HOURS |
|----|------------|--------------|
| 1 | 2014-12-14 | 15.00 hour |
| 1 | 2014-12-15 | 24.00 hour |
| 1 | 2014-12-16 | 24.00 hour |
| 1 | 2014-12-17 | 3.50 hour |
| 2 | 2014-12-20 | 6.50 hour |