且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PostgreSQL中按月和年分组查询结果

更新时间:2023-01-29 20:57:02

select to_char(date,'Mon') as mon,
       extract(year from date) as yyyy,
       sum("Sales") as "Sales"
from yourtable
group by 1,2

应Radu的要求,我将解释该查询:

At the request of Radu, I will explain that query:

to_char(日期,'Mon')as mon,:将 date属性转换为月的简短形式的定义格式。

to_char(date,'Mon') as mon, : converts the "date" attribute into the defined format of the short form of month.

extract(从日期开始的年)为yyyy :Postgresql的 extract函数用于从 date属性中提取YYYY年。

extract(year from date) as yyyy : Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.

sum( Sales)as Sales :SUM()函数将所有 Sales值相加,并提供区分大小写的别名,

sum("Sales") as "Sales" : The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.

group by 1,2 :GROUP BY函数必须包含SELECT列表中不属于聚合的所有列(也就是,不在SUM / AVG / MIN / MAX等函数内的所有列)。这告诉查询应该将SUM()应用于每个唯一的列组合,在这种情况下为月和年列。尽管可能***使用完整的 to_char(...)和 extract(...)表达式,但 1,2部分是简化的方式,而不是使用列别名。

group by 1,2 : The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.