向此 group by 语句添加条件
我有一个由名字、姓氏和日期组成的表,如下所示:
_________
| People |____________________________________
|----------------------------------------------|
| first_name | last_name | date |
|----------------------------------------------|
| Jerry Garcia 01/01/2001 |
| Adam Garcia 01/02/2001 |
| Hans Fist 01/02/2001 |
| Lucy Fist 01/02/2001 |
|______________________________________________|
我有一个像这样的 group by 和 order by 语句:
$this->db->group_by("date, last_name");
$this->db->order_by('date ASC');
因此,很自然地,您会期望它只为两个 Garcia 和一个提供一行排两个拳头。我想做的,并记住这是一个非常简单的情况,是按姓氏分组,但如果 last_name = 'Garcia'
不要。因此,您会在结果集中看到两个加西亚和一个拳头。
我该怎么做?
如果它像GROUP BY date, last_name NOT 'Garcia'这样简单就好了
I have a table consisting of First Name, Last Name, and Date, like this:
_________
| People |____________________________________
|----------------------------------------------|
| first_name | last_name | date |
|----------------------------------------------|
| Jerry Garcia 01/01/2001 |
| Adam Garcia 01/02/2001 |
| Hans Fist 01/02/2001 |
| Lucy Fist 01/02/2001 |
|______________________________________________|
And I have a group by and order by statement like this:
$this->db->group_by("date, last_name");
$this->db->order_by('date ASC');
So naturally, you would expect it to only give you one row for the two Garcia's and one row for the two Fist's. What I'd like to do, and keep this in mind this is a very simplified case, is to group by last name, but if last_name = 'Garcia'
DONT. So you'd see both garcias and only one fist in the result set.
How do I do this?
If only it were as simple as GROUP BY date, last_name NOT 'Garcia'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许您可以在第一个查询中添加类似的内容
,然后执行
Maybe you can add to your first query something like
And then, do
您应该能够摆脱
GROUP BY
并仅使用ORDER BY last_name DESC, date ASC
。请注意,如果您有想要解决的特定问题,请将其与问题一起发布。你会得到更好的答案!
You should be able to get rid of the
GROUP BY
and just useORDER BY last_name DESC, date ASC
.Note that if you have a specific problem you are trying to solve, post that with the question. You'll get a much better answer!
您可以使用
HAVING
在GROUP BY
子句上使用条件。然后,您可以使用UNION
关键字连接两个结果集。You can use conditions on the
GROUP BY
clause usingHAVING
. You can then join two result sets using theUNION
keyword.我自己想出了一个解决方案。对于遇到类似情况的任何人,只需在查询的
SELECT
部分中使用CASE/WHEN
语句即可。您可以将其用作每行上的布尔标志以进行分组。
I came up with a solution myself. For anyone who finds themselves in a similar situation, just use a
CASE/WHEN
statement in theSELECT
portion of your query.You can use that as a boolean flag on each row to group by.