开发者

MySQL grouping by a previously declared alias, what do I wrap it in? ' OR `

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

SELECT CONCAT(YEAR(r.Date),_u开发者_如何学Ctf8'-',_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


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.


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜