当前日期和上周之间的SQL查询

时间:2012-03-07 09:45:25

标签: sql postgresql

SELECT sge_job.j_owner AS "Owner"
      ,SUM(sge_job_usage.ju_cpu) AS "CPU Total"
FROM sge_job_usage, sge_job 
GROUP BY j_owner;

这是我当前的sql查询,它只是简单地读取CPU%和作业所有者,但是如果它在当前日期之间说14天(2周)之前我只能合并上面的总和。

sge_job_usage表中属于:

ju_start_timeju_end_time

任何人都可以帮助我了解我是如何检查它是否在当前日期之间 - 前14天然后检查end_time日期以查看它是否仍然存在?

Answer that Outputs What I need below:

SELECT sge_job.j_owner AS "Owner"       
,SUM(sge_job_usage.ju_cpu) AS "CPU Total" 
FROM sge_job_usage, sge_job  
WHERE ju_start_time BETWEEN LOCALTIMESTAMP - INTERVAL '1 week' AND LOCALTIMESTAMP 
GROUP BY j_owner;

3 个答案:

答案 0 :(得分:12)

ADC语法对PostgreSQL无效。

我不明白您希望将哪种条件应用于ju_end_date。但它应该类似于ju_start_time上的那个。

SELECT sge_job.j_owner AS "Owner"
      ,SUM(sge_job_usage.ju_cpu) AS "CPU Total"
FROM sge_job_usage, sge_job 
WHERE sge_job_usage.C1 = sge_job.C2
  AND ju_start_time BETWEEN LOCALTIMESTAMP - INTERVAL '14 days' AND LOCALTIMESTAMP
GROUP BY j_owner;

我没有测试环境,所以我无法测试,但我认为它应该可行。

有关主题检查的更多信息

http://www.postgresql.org/docs/9.1/static/functions-datetime.html

编辑:正如所说的ypercube,你需要在两个表上加入条件。

答案 1 :(得分:4)

我假设这两列是DATE类型。那么你需要这样的东西:

WHERE ju_start_time BETWEEN CURRENT_DATE - INTERVAL '14 days'
                        AND CURRENT_DATE
  AND ju_end_time >= CURRENT_DATE

或者这(取决于你想要检查的条件:

WHERE ( ju_start_time, ju_end_time ) 
      OVERLAPS 
      ( CURRENT_DATE - INTERVAL '14 days', CURRENT_DATE )

查询使用2个表但没有条件用于Join。它应该是:

SELECT sge_job.j_owner AS "Owner"
      ,SUM(sge_job_usage.ju_cpu) AS "CPU Total"
FROM sge_job_usage
  JOIN sge_job
    ON sge_job.SomeColumn = sge_job_usage.SomeColumn 
WHERE   ...
GROUP BY j_owner;

答案 2 :(得分:2)

目前尚不清楚ju_end_date是否需要相同的条件,但结构应该是:

...
WHERE ju_start_time BETWEEN getdate() and DateAdd(d,-14, getdate())