从月份开始日期开始跟踪周间隔
Track the week intervals from the month start date
我试图找出从 2021 年 1 月 1 日开始的每 1 周期间有多少跑步者报名。我对查询没有任何问题,但我无法使用达到 7 天数字标记的日期来完成我的查询。mod (%)。
---My Schema
CREATE TABLE runners (
"runner_id" INTEGER,
"registration_date" DATE
);
INSERT INTO runners
("runner_id", "registration_date")
VALUES
(1, '2021-01-01'),
(2, '2021-01-03'),
(3, '2021-01-08'),
(4, '2021-01-15');
runner_id registration_date
1 2021-01-01
2 2021-01-03
3 2021-01-08
4 2021-01-15
想要O/P:
start_of_week signups
2021-01-01 2
2021-01-08 1
2021-01-15 1
---My Query
WITH data1 AS (
SELECT
runner_id,
registration_date,
REGISTRATION_DATE - (DATEDIFF(DAY, REGISTRATION_DATE, '2021-01-01' ) % 7) AS start_of_week
FROM runners
)
select start_of_week, count(runner_id) as signup from data1 group by start_of_week;
错误
Operand type clash: date is incompatible with int
我也尝试将日期格式切换为 mod 和 7 但没有用。
registration_date - ((registration_date - '2021-01-01') % 7)
错误
The data types date and varchar are incompatible in the subtract operator.
根据评论,试试这个:
WITH data1 AS (
SELECT
runner_id,
registration_date,
(datediff(DAY, '2021-01-01',REGISTRATION_DATE ) / 7) + 1 AS start_of_week
FROM runners
)
select
dateadd(week, start_of_week - 1, '2021-01-01'),
count(runner_id) as signup
from data1
group by start_of_week;
dbfiddle
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=91a00cf6223f3c1367b6e8f014dccd6f
如果你想摆脱时间,你也可以将它转换为日期
select
cast(dateadd(week, start_of_week - 1, '2021-01-01') as date),
count(runner_id) as signup
from data1
group by start_of_week;
我试图找出从 2021 年 1 月 1 日开始的每 1 周期间有多少跑步者报名。我对查询没有任何问题,但我无法使用达到 7 天数字标记的日期来完成我的查询。mod (%)。
---My Schema
CREATE TABLE runners (
"runner_id" INTEGER,
"registration_date" DATE
);
INSERT INTO runners
("runner_id", "registration_date")
VALUES
(1, '2021-01-01'),
(2, '2021-01-03'),
(3, '2021-01-08'),
(4, '2021-01-15');
runner_id registration_date
1 2021-01-01
2 2021-01-03
3 2021-01-08
4 2021-01-15
想要O/P:
start_of_week signups
2021-01-01 2
2021-01-08 1
2021-01-15 1
---My Query
WITH data1 AS (
SELECT
runner_id,
registration_date,
REGISTRATION_DATE - (DATEDIFF(DAY, REGISTRATION_DATE, '2021-01-01' ) % 7) AS start_of_week
FROM runners
)
select start_of_week, count(runner_id) as signup from data1 group by start_of_week;
错误
Operand type clash: date is incompatible with int
我也尝试将日期格式切换为 mod 和 7 但没有用。
registration_date - ((registration_date - '2021-01-01') % 7)
错误
The data types date and varchar are incompatible in the subtract operator.
根据评论,试试这个:
WITH data1 AS (
SELECT
runner_id,
registration_date,
(datediff(DAY, '2021-01-01',REGISTRATION_DATE ) / 7) + 1 AS start_of_week
FROM runners
)
select
dateadd(week, start_of_week - 1, '2021-01-01'),
count(runner_id) as signup
from data1
group by start_of_week;
dbfiddle
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=91a00cf6223f3c1367b6e8f014dccd6f
如果你想摆脱时间,你也可以将它转换为日期
select
cast(dateadd(week, start_of_week - 1, '2021-01-01') as date),
count(runner_id) as signup
from data1
group by start_of_week;