sql基于时间序列对相同值进行分区的最佳策略

时间:2018-09-21 22:56:57

标签: sql oracle

我的数据看起来像这样,其中每个ID都有多个与升序日期变量相对应的值:

<button onclick="myfunction();">Go</button>

<div class="tablecontainer" style="display: none;">

  <table id="table" border=1>
    <tr>
      <th> booking_address </th>
      <th> booking_date </th>
      <th> booking_message </th>
      <th>request date and time </th>
      <th> requested_tech_1 </th>
      <th> requested_tech_2 </th>
      <th>requested_tech_3 </th>
      <th>xyz</th>
      <th>abc</th>
    </tr>
  </table>
</div>

我想获取每个ID / LEVEL / DATE块的计数,如下所示:

ID  LEVEL  DATE
1   10     10/1/2000
1   10     11/20/2001
1   10     12/01/2001
1   30     02/15/2002
1   30     02/15/2002
1   20     05/17/2002
1   20     01/04/2003
1   30     07/20/2003
1   30     03/16/2004
1   30     04/15/2004

问题是,如果我使用计数窗口功能并按级别划分,则无论时间顺序如何,它将30组合在一起。我希望20级之前和之后的30级计数是不同的。有谁知道这是怎么做到的吗?

1 个答案:

答案 0 :(得分:2)

使用function StaticCacheClear() { foreach (scandir(sys_get_temp_dir()) as $file) { if (StringBeginsWith($file, "staticcache")) { $path = sys_get_temp_dir() ."/". $file; unlink($path); } } global $Memcache; if ($Memcache) $Memcache->flush(); } // REMOVE if you don't want a global way to clear cache if (isset($_GET['clear_static_cache'])) { StaticCacheClear(); } function MemcacheGet($key) { global $Memcache; $value = $Memcache ? $Memcache->get($key) : (file_exists($key)?file_get_contents($key):null); return !$Memcache? $value : (Memcached::RES_NOTFOUND === $Memcache->getResultCode() ? null : $value); } function StaticCacheKey($key) { global $Memcache; $cacheVersion = "MY_APP_VERSION_HERE"; $uniqueKey = "staticcache_{$key}_" . date("Ymd") . "$cacheVersion.cache"; $filename = sanitize_file_name($uniqueKey); $filename = sys_get_temp_dir() . '/' . $filename; return $Memcache ? $uniqueKey : $filename; } function StaticCacheWrite($key, $value) { global $Memcache; if (isset($_GET['disable-cache'])) return null; if ($Memcache) $Memcache->set(StaticCacheKey($key), serialize($value)); else file_put_contents(StaticCacheKey($key), serialize($value)); } function StaticCacheRead($key) { global $Memcache; $key = StaticCacheKey($key); $value = MemcacheGet($key); return $value !== null ? unserialize($value) : null; } 的标准gaps and islands解决方案,如果您的特定DBMS上有此解决方案...

ROW_NUMBER()

可视化两个行号的效果...

WITH
  ordered AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY id        ORDER BY date)   AS set_ordinal,
    ROW_NUMBER() OVER (PARTITION BY id, level ORDER BY date)   AS grp_ordinal
  FROM
    yourData
)
SELECT
  id,
  level,
  set_ordinal - grp_ordinal,
  MIN(date),
  COUNT(*)
FROM
  ordered
GROUP BY
  id,
  level,
  set_ordinal - grp_ordinal
ORDER BY
  id,
  MIN(date)