有一个具有日期和cnt列的表,例如
12-OCT-15 12-OCT-15 19-OCT-15 19-OCT-15 27-OCT-15 30-OCT-15 04-NOV-15 05-NOV-15 12-NOV-15 12-NOV-15
可以使用:-
创建此表timestamp cnt
------------------
1547015021 14
1547024080 2
结果应为时间戳与提供的时间戳列表最接近的行的 cnt 列的总和。提供的数据可能是
DROP TABLE IF EXISTS roundit_base;
CREATE TABLE IF NOT EXISTS roundit_base (timestamp INTEGER, cnt INTEGER);
INSERT INTO roundit_base VALUES (1547015021,14),(1547024080,2);
结果应该与
相似1546905600 - 0
1546992000 - 0
1547078400 - 0
...
这是两列:-
答案 0 :(得分:1)
尽管结果与预期结果不同,因为使用的计算将 1547015021 和 1547024080 都设置为最接近 1546992000的时间戳 strong>;
以下内容可能是基于SQLite的解决方案的基础:-
WITH
-- The supplied list of timestamps
v (cv,dflt) AS (
VALUES (1546905600,0),(1546992000,0),(1547078400,0)
),
-- Join the two sets calculating the difference
cte1 AS (
SELECT *, abs(cv - timestamp) AS diff FROM roundit_base INNER JOIN v
),
-- Find the closest (smallest difference) for each timestamp
cte2 AS (
SELECT *, min(diff) FROM cte1 GROUP BY timestamp
)
-- For each compartive value sum the counts allocated/assigned (timestamps) to that
SELECT cv,
CASE
WHEN
(SELECT sum(cnt) FROM cte2 WHERE cv = v.cv) IS NOT NULL
THEN
(SELECT sum(cnt) FROM cte2 WHERE cv = v.cv)
ELSE 0
END AS cnt
FROM v;
;
以上结果为:-