嗨,我在按月份对图像数据进行排序时遇到了麻烦,我想通过获取计数和按月的分组来确定在某个月份内创建,更新和删除了多少张图像。我有两个包含图像数据的表。两个表都有'createdAt','updatedAt'和'deletedAt'列,所以我所做的是将两个表的列设置为日期格式,并将它们合并为所有数据,但是我无法获取数据计数。这是我到目前为止的内容:
SELECT DATE_FORMAT(`createdAt`, "%M %Y"), DATE_FORMAT(`updatedAt`, "%M %Y"), DATE_FORMAT(`deletedAt`, "%M %Y") FROM harvest_sample_images UNION SELECT DATE_FORMAT(`createdAt`, "%M %Y"), DATE_FORMAT(`updatedAt`, "%M %Y"), DATE_FORMAT(`deletedAt`, "%M %Y") FROM plant_sample_images
任何帮助将不胜感激。
SELECT DATE_FORMAT(`createdAt`, "%M %Y") DAT, count(*) AS `created`,
(SELECT DATE_FORMAT(`updatedAt`, "%M %Y") DAT, COUNT(*)) AS `updated`,
(SELECT DATE_FORMAT(`deletedAt`, "%M %Y") DAT COUNT(*)) AS `deleted`
FROM (SELECT `createdAt`, `updatedAt`, `deletedAt` FROM harvest_sample_images UNION SELECT `createdAt`, `updatedAt`, `deletedAt` FROM plant_sample_images)
GROUP BY DATE_FORMAT(`created`, "M% %Y")
我已经尝试过了。
所以我可能已经找到了另一种方法,将图像信息与计数分别显示在每个月中,并显示其所属月份。
SELECT DATE_FORMAT(`timestamp_date`, "%M %Y") AS `Month`,
(SELECT COUNT(*) FROM (SELECT `createdAt` FROM harvest_sample_images UNION ALL SELECT `createdAt` FROM plant_sample_images) AS `images_created` WHERE DATE_FORMAT(images_created.`createdAt`, "%m %y") = DATE_FORMAT(`timestamp_date`, "%m %y")) AS `Created`,
(SELECT COUNT(*) FROM (SELECT `updatedAt` FROM harvest_sample_images UNION ALL SELECT `updatedAt` FROM plant_sample_images) AS `images_updated` WHERE DATE_FORMAT(images_updated.`updatedAt`, "%m %y") = DATE_FORMAT(`timestamp_date`, "%m %y")) AS `Updated`,
(SELECT COUNT(*) FROM (SELECT `deletedAt` FROM harvest_sample_images UNION ALL SELECT `deletedAt` FROM plant_sample_images) As `images_deleted` WHERE DATE_FORMAT(images_deleted.`deletedAt`, "%m %y") = DATE_FORMAT(`timestamp_date`, "%m %y")) AS `Deleted`
FROM table_dates
所以我现在要做的是,创建了另一个表,该表的日期列表从数据的开始到现在。然后,我遍历数据并检查table_dates的格式化日期是否等于两个图像表date的并集的格式化日期。我得到计数并将其添加为新表中的列。 思想得到赞赏
答案 0 :(得分:1)
您需要计数和分组
select year(createdAt) year , month(createdAt) month, count(*)
from my_table
group by year(createdAt), month(createdAt)
或
SELECT DATE_FORMAT(`createdAt`, "%M %Y") DAT, count(*)
from my_table
group by DATE_FORMAT(`createdAt`, "%M %Y")
您可以使用join的3个计数
select t1.year_month, t1.count_create, t2.count_update, t3count_delete
from (
SELECT DATE_FORMAT(`createdAt`, "%M %Y") year_month , count(*) count_create
from my_table
group by DATE_FORMAT(`createdAt`, "%M %Y")
) t1
left join (
SELECT DATE_FORMAT(`updatedAt`, "%M %Y") year_month , count(*) count_update
from my_table
group by DATE_FORMAT(`updatedAt`, "%M %Y")
) t2 ON t1.year_month = t2.year_month
left join (
SELECT DATE_FORMAT(`deletedAt`, "%M %Y") year_month , count(*) count_delete
from my_table
group by DATE_FORMAT(`deletedAt`, "%M %Y")
) t3 ON t1.year_month = t3.year_month