MySQL 按先前声明的别名进行分组,我该如何将其包装起来? '或`

发布于 2024-08-27 16:42:06 字数 348 浏览 3 评论 0原文

我有一个 SQL 查询,它在 SELECT 语句中有一个别名

选择 CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'

稍后,我想在我的 group by 语句中引用此内容。

我有点困惑...我应该用反引号、单引号将其括起来,还是直接将其展开到 group by

GROUP BY 中 ``QuarterYear

还是我应该这样做?: 分组依据 “QuarterYear”

还是这个?: 分组依据 季度年

I have an SQL query that has an alias in the SELECT statement

SELECT
CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'

Later, I want to refer to this in my group by statement.

I'm a little confused...should I wrap this with backticks, single quote or just leave it unwrapped int he group by

GROUP BY
``QuarterYear

or should I do this?:
GROUP BY
'QuarterYear'

or just this?:
GROUP BY
QuarterYear

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

じ违心 2024-09-03 16:42:06

您可以使用反引号转义别名或列名称,但仅当您的列具有保留字作为其名称(即 timestamp)时才需要,因此您不需要这样做。避免使用保留字,这样您就永远不需要用反引号转义列名。

你不应该使用单引号来包裹列名,这仅适用于数据。

编辑:您不能按组列的别名进行分组(即MIN()MAX()COUNT()< /code> 等),但可以使用函数别名(即 CONCAT())。

You can escape aliases or column names using a backtick but it's only required when your column has a reserved word as its name (i.e. timestamp), so you don't need to. Avoid using reserved words instead, so you'll never need to escape column names with backticks.

You should never use single quotes to wrap column names, this is only for data.

EDIT: You can't group by aliases of group columns (i.e. MIN(), MAX(), COUNT() etc) but using aliases of functions (i.e. CONCAT()) you can.

余生一个溪 2024-09-03 16:42:06

不幸的是,您无法使用别名,因为别名在 GROUP BY 中尚不可用。不过,您可以使用列号:

SELECT CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'
GROUP BY 1;

在这种特殊情况下,您可以只使用 DISTINCT 修饰符:

SELECT DISTINCT CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'

Unfortunatelly, you can not use the alias because the alias is not yet available in GROUP BY. You can use the number of the column though:

SELECT CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'
GROUP BY 1;

In this particular case you can just use DISTINCT modifier:

SELECT DISTINCT CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文