gpt4 book ai didi

mysql - SQL CASE,当列类别 = x 按类别分组时,否则不分组

转载 作者:行者123 更新时间:2023-11-29 01:20:30 25 4
gpt4 key购买 nike

我有这张表:

date           client        category
-------------------------------------
2016-05-20 harrys bar
2016-05-20 pitchers bar
2016-05-20 eagle sport
2016-05-21 claire other
2016-05-21 maximus other
2016-05-24 eagle sport
2016-05-24 dolphin sport

现在的结果是:

date           client        category
-------------------------------------
2016-05-20 harrys bar (two rows)
2016-05-20 eagle sport
2016-05-21 claire other (two rows)
2016-05-24 eagle sport (two rows)

因为我对列类别进行了分组,但我希望结果是:

date           client        category
-------------------------------------
2016-05-20 harrys bar (two rows)
2016-05-20 eagle sport
2016-05-21 claire other
2016-05-21 maximus other
2016-05-24 eagle sport
2016-05-24 dolphin sport

因此,当日期和类别“bar”匹配时,我希望它们分组。但我不希望在日期匹配时将类别“运动”或“其他”分组。

我试过锁定CASE-WHEN-THEN-ELSE..等。但是我就是不知道怎么写sql语句。

我试过类似的东西

SELECT *
FROM events
GROUP BY
CASE
WHEN category = "bar" THEN category ELSE ""
END

它给我:

date           client        category
-------------------------------------
2016-05-20 harrys bar
2016-05-20 eagle sport

我也试过

WHEN category = "bar" THEN date, category ELSE ""

但是根本没用..

如您所见,我不知道如何使用 CASE...所以有什么建议吗?

我已经尝试阅读 stackoverflow 上的许多问题以及 SQL 语句等手册。我只是不明白如何使用它。

最佳答案

你可以使用UNION ALL:

SELECT category, date, client
FROM events
WHERE category <> 'bar'
UNION ALL
SELECT category, date, MIN(client) AS client
FROM events
WHERE category = 'bar'
GROUP BY category, date;

LiveDemo

关于mysql - SQL CASE,当列类别 = x 按类别分组时,否则不分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37321950/

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