2

我在编写正确的 sql 查询时遇到问题,该查询应按国家和站点选择两个日期之间的最小/最大/平均持续时间(以天为单位)以进行试验。

我的查询:

SELECT v.country as country, v.site as site,
  COUNT(*) as N --,
  --MAX(list of durations in days between discovered date to repored date on each violation by country and site) as "Maximum",
  --MIN(list of durations in days between discovered date to repored date on each violation by country and site) as "Minimum",
  --AVG(list of durations in days between discovered date to repored date on each violation by country and site) as "Mean"
FROM violations v
WHERE v.trial_id = 3
GROUP BY ROLLUP (v.country, v.site)

这是我的SQLFIDDLE,其中包含改进注释行所需的数据结构和查询。

请问你能帮帮我吗?

4

2 回答 2

5

使用 Oracle,日期存储为偏移量,因此您可以简单地从另一个日期中减去 1 个日期。有关详细信息,请参阅日期算术

SQLFiddle

SELECT v.country as country, v.site as site,
  COUNT(*) as N,
  MAX(reporded_date - discovered_date) as "Maximum",
  MIN(reporded_date - discovered_date) as "Minimum",
  AVG(reporded_date - discovered_date) as "Mean"
FROM violations v
WHERE v.trial_id = 3
GROUP BY ROLLUP (v.country, v.site)

请注意,您提供的测试数据总是相隔 1 天,所以我也在我的小提琴中更新了(对于德国)。

于 2013-03-14T11:25:35.520 回答
0

您所要做的就是将报告日期和发现日期之间的差异放入聚合函数中:

SELECT v.country as country, v.site as site,
  COUNT(*) as N,
  MAX(reported_date-discovered_date) as "Maximum",
  MIN(reported_date-discovered_date) as "Minimum",
  AVG(reported_date-discovered_date) as "Mean"
FROM violations v
WHERE v.trial_id = 3
GROUP BY ROLLUP (v.country, v.site)

您提供的 SQLFiddle 数据实际上不会显示任何差异,因此这里是一个更新版本

于 2013-03-14T11:32:42.457 回答