gpt4 book ai didi

mysql - SQL按天划分多条记录

转载 作者:行者123 更新时间:2023-11-29 05:50:32 24 4
gpt4 key购买 nike

我的 SQL 表的结构非常简单,只包含 3 个字段:

createDate(Date): time when record inserted;
title(String): title for record;
count(Integer32): count for record;

表中有10w+条记录!表示一年内插入的记录:

  • 任意一天可以插入任意条记录(包括0条记录)

那么,我怎样才能按天划分记录呢???

例:表中有10条记录:

1. 2019-01-01 10:20:15 xxx
2. 2019-01-01 12:50:10 xxx
3. 2019-01-01 23:20:19 xxx

4. 2019-01-02 10:20:15 xxx

5. 2019-01-05 08:20:15 xxx
6. 2019-01-05 22:20:15 xxx

7. 2019-02-10 10:20:15 xxx
8. 2019-02-10 11:20:15 xxx
9. 2019-02-10 15:20:15 xxx

10. 2019-02-15 10:20:15 xxx

我想要结果:分成 5 个“集合”

集合“2019-01-01”(包含 3 条记录):

- 2019-01-01 10:20:15 xxx
- 2019-01-01 12:50:10 xxx
- 2019-01-01 23:20:19 xxx

集合“2019-01-02”(包含 1 条记录):

- 2019-01-02 10:20:15 xxx

集合“2019-01-05”(包含 2 条记录):

- 2019-01-05 08:20:15 xxx
- 2019-01-05 22:20:15 xxx

集合“2019-02-10”(包含 3 条记录):

- 2019-02-10 10:20:15 xxx
- 2019-02-10 11:20:15 xxx
- 2019-02-10 15:20:15 xxx

集合“2019-02-15”(包含 1 条记录):

- 2019-02-15 10:20:15 xxx

最佳答案

如果我的表架构正确,那么这将是您可能的解决方案。

    GO

CREATE TABLE #tempRequestForMeList
(
createDate datetime,
title nvarchar(50),
[count] int
)

GO

insert into #tempRequestForMeList ( createDate, title, [count] )
values ( '2016-09-20 17:17:04.840', 'dd', 0 )
, ( '2016-09-20 17:17:04.840', 'dd', 1 )
, ( '2016-09-20 07:17:04.840', 'dd', 1 )
, ( '2016-09-20 05:17:04.840', 'dd', 1 )
, ( '2016-09-20 13:17:04.840', 'dd', 1 )
, ( '2016-09-19 12:17:04.840', 'dd', 1 )
, ( '2016-09-19 02:17:04.840', 'dd', 1 )
, ( '2016-09-19 01:17:04.840', 'dd', 1 )
, ( '2016-09-18 02:17:04.840', 'dd', 1 )
, ( '2016-09-18 03:17:04.840', 'dd', 1 )
, ( '2016-09-18 05:17:04.840', 'dd', 1 )
, ( '2016-09-18 07:17:04.840', 'dd', 1 )

GO
; with cte as (
select cast(createdate as date) as Date1, * from #tempRequestForMeList )
update dd set dd.[count] = ct.co from #tempRequestForMeList as dd inner join (select count(date1) as co, date1 from cte group by Date1) as ct on cast(dd.createDate as DATE) = ct.Date1

select * from #tempRequestForMeList --- if require count with each row

go

drop table #tempRequestForMeList
go

如果这不起作用,则显示您的表架构和预期输出。

注意:这是针对 SQL 服务器的

关于mysql - SQL按天划分多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com