Mysql 按“分组查询结果”;今天",&引用;“在过去7天内”&引用;“上个月”;及;“老年人”;
我有一个简单的问题,关于用一些“叙述性”句点按日期分组行。 让我们假设我有一个非常简单的包含文章的表。ID,即主键、标题和日期。日期列是datetime/timestamp 我想以某种方式将我的结果分组,这样我就可以像 今天写:Mysql 按“分组查询结果”;今天",&引用;“在过去7天内”&引用;“上个月”;及;“老年人”;,mysql,sql,database,group-by,Mysql,Sql,Database,Group By,我有一个简单的问题,关于用一些“叙述性”句点按日期分组行。 让我们假设我有一个非常简单的包含文章的表。ID,即主键、标题和日期。日期列是datetime/timestamp 我想以某种方式将我的结果分组,这样我就可以像 今天写: 第944条 第943条 在过去7天内编写: 第823条 第743条 在过去30天内撰写: 第520条 第519条 第502条 较老的: 第4条 第3条 第1条 我可以用一些GROUPBY语句在一个查询中实现这一点吗?您可以使用case语句作为分组列。大概
- 第944条
- 第943条
- 第823条
- 第743条
- 第520条
- 第519条
- 第502条
- 第4条
- 第3条
- 第1条
我可以用一些GROUPBY语句在一个查询中实现这一点吗?您可以使用
case
语句作为分组列。大概是这样的:
select (case when date = curdate() then 'today'
when date >= curdate() - interval 6 day then 'last 7 days'
when date >= curdate() - interval 29 day then 'last 30 days'
else 'older'
end),
count(*),
. . .
from . . .
group by (case when date = curdate() then 'today'
when date >= curdate() - interval 6 day then 'last 7 days'
when date >= curdate() - interval 29 day then 'last 30 days'
else 'older'
end)
戈登写这篇文章应该是有功劳的。但我认为您可能只是想用适当的描述符附加一列,并可能按照您希望看到的顺序对它们进行排序
select
title,
case when date = curdate() then 'today'
when date >= curdate() - interval 6 day then 'last 7 days'
when date >= curdate() - interval 29 day then 'last 30 days'
else 'older'
end as bucket,
from ...
order by
case
when date = curdate() then 1
when date >= curdate() - interval 6 day then 2
when date >= curdate() - interval 29 day then 3
else 4
end,
title ...
看起来你没有按字母顺序排列标题。如果要按年龄对它们进行排序,请删除大小写表达式,只使用日期值。谢谢。它是如此简单。。。 这正是我想要的
select
id,
title,
published_at,
(case
when published_at > curdate() then 'future article'
when published_at = curdate() then 'today'
when published_at >= curdate() - interval 6 day then 'last 7 days'
when published_at >= curdate() - interval 29 day then 'last 30 days'
else 'older'
end) as 'when'
from
articles
order by
published_at desc
OP确实需要行详细信息,所以我认为您不想聚合。返回计算表达式和排序可能就足够了。@shawnt00。嗯,问题是“我想以某种方式将我的结果分组”,然后明确提到
group by
。我知道。还有BI工具,它们使用“组”这个术语来指代带有组页眉/页脚的排序数据的概念。确切地案件已结案。谢谢你们两位。