你可以做这样的事情,给你上面提供的数据;
CREATE TABLE Transactions (
id INT PRIMARY KEY ,
actual_date DATE
);
INSERT INTO Transactions (id, actual_date) VALUES
(1, '2017-01-31'),
(2, '2017-01-30'),
(3, '2017-01-30'),
(4, '2017-01-30'),
(5, '2017-02-04'),
(6, '2017-02-05'),
(7, '2017-02-06'),
(8, '2017-02-10'),
(9, '2017-02-08'),
(10, '2017-02-06'),
(11, '2017-02-12'),
(12, '2017-02-06'),
(13, '2017-02-06'),
(14, '2017-02-12'); `
执行以下查询对于PostgreSQL:
SELECT
actual_date as "Acutal_Date",
extract(week FROM actual_date) as "Week_Number",
SUM(
COUNT(*))
OVER (
PARTITION BY extract(week FROM actual_date)
ORDER BY actual_date
) as "Weekly_Count"
FROM
Transactions
GROUP BY actual_date
ORDER BY actual_date;
或者,如果使用MySQL,使用:
SELECT
actual_date as "Actual_Date",
WEEKOFYEAR(actual_date) as "Week_Number",
(SELECT
COUNT(*)
FROM
Transactions T
WHERE
WEEKOFYEAR(T.actual_date) = WEEKOFYEAR(Transactions.actual_date) AND
T.actual_date <= Transactions.actual_date) as "Weekly_Count"
FROM
Transactions
GROUP BY actual_date
ORDER BY actual_date;
会产生:
┌─────────────┬─────────────┬──────────────┐
│ Acutal_Date │ Week_Number │ Weekly_Count │
├─────────────┼─────────────┼──────────────┤
│ 2017-01-30 │ 5 │ 3 │
│ 2017-01-31 │ 5 │ 4 │
│ 2017-02-04 │ 5 │ 5 │
│ 2017-02-05 │ 5 │ 6 │
│ 2017-02-06 │ 6 │ 4 │
│ 2017-02-08 │ 6 │ 5 │
│ 2017-02-10 │ 6 │ 6 │
│ 2017-02-12 │ 6 │ 8 │
└─────────────┴─────────────┴──────────────┘
你不能硬编码星期的范围和数量? –
我可以做到这一点,但有时我们有零交易,我想让这个过程自动化,而不是每次都改变日期。这是我的扩展的SQL脚本的一小部分,我很难解决这部分。 –
'select count(*)from tablename where actual_date> = date'2017-02-06'and actual_date <= date'2017-02-12'' –