【发布时间】:2023-02-05 00:58:23
【问题描述】:
正如主题所述,我有一个每个用户有多行的表,我需要为每个用户获取所有行的计数,其中包含日期最早的行中的数据,然后插入一个新行,其中包含计数值另一张桌子。
我正在将出勤列表 CSV 文件导入到临时表中...工作正常。但是现在我需要将所有单独的记录处理成一个要添加到最终表中的汇总记录。
tempTable:
id email tDate cValue col4 col5 col6
==========================================================
1 a@a.com 2021-01-01 1 foo bar foobar
2 b@b.com 2021-01-02 1 bar foo barfoo
3 a@a.com 2021-02-01 1 foo bar foobar
4 c@c.com 2021-01-15 1 bah hab bahhab
5 d@d.com 2021-02-15 1 hab bah habbah
5 b@b.com 2021-03-01 1 bar foo barfoo
6 a@a.com 2021-04-01 1 foo bar foobar
7 d@d.com 2021-03-01 1 hab bah habbah
newTable (with newest date)
id email tDate cValue col4 col5 col6
==========================================================
1 a@a.com 2021-04-01 3 foo bar foobar
2 b@b.com 2021-03-01 2 bar foo barfoo
3 c@c.com 2021-01-15 1 bah hab bahhab
4 d@d.com 2021-03-01 2 hab bah habbah
我认为下面的方法有效(我已经测试了 select 部分,但还没有测试完整的 insert),但我不知道如何根据 tDate 是最旧还是最新来处理 GROUP BY email。我还没有决定最旧或最新的数据应该在哪里作为最终记录——但我仍然需要知道如何在日期之前抓取。
INSERT INTO newTable (email,tDate,cValue,col4,col5,col6)
SELECT
email,
tDate,
COUNT(*) as tValue,
col4,
col5,
col6
FROM tempTable
GROUP BY email ;
当我执行 ORDER BY tDate DESC 时 - 它只是对输出进行排序,而不是实际对 GROUP BY 之前的记录进行排序。
【问题讨论】:
-
因为你只有
GROUP BY email,MySQL 不知道要返回哪个tDate(我正在使用默认的 8.0x 安装)它应该返回MIN(tDate)或MAX(tDate),还是使用任何其他 aggregate function ? (这同样适用于 col4、col5 和 col6)(请参阅错误“SELECT 列表的表达式 #2 不在 GROUP BY 子句中并且包含非聚合列‘fiddle.tempTable.tDate’,它不是 ..... GROUP BY 子句; 这与 sql_mode=only_full_group_by 不兼容": DBFIDDLE) -
@Luuk - 奇怪。我在我自己的数据库上运行查询并且它有效。我没有收到您的 DBFiddle 中列出的错误。我想知道为什么?这有效:
INSERT INTO newTable (email,tDate,cValue,col4,col5,col6) SELECT email,MIN(tDate),COUNT(*) as tValue,col4,col5,col6 FROM tempTable GROUP BY email ;
标签: mysql group-by count sql-insert