[英]How to convert DATETIME from YYYY-MM-DD HH:MI:SS. to YYYY-MM using SQL
Using a platform that supports Oracle, SQL Server, IBM DB2, MySQL, Sybase, Informix, PostgreSQL and ANSI SQL dialects. Using a platform that supports Oracle, SQL Server, IBM DB2, MySQL, Sybase, Informix, PostgreSQL and ANSI SQL dialects.
I need to be able to group customer sales by year and month.我需要能够按年和月对客户销售进行分组。 The desired date format is YYYY-MM eg 2019-06.所需的日期格式为 YYYY-MM,例如 2019-06。 The current format is YYYY-MM-DD HH:MI:SS.当前格式为 YYYY-MM-DD HH:MI:SS。
Below is what I have so far.以下是我到目前为止所拥有的。 I have tried many different things but unable to get to work as desired.我尝试了许多不同的事情,但无法按要求开始工作。
SELECT DISTINCT "Customer Name",
ROUND(SUM("Price Ex"), 2) AS 'Sales'
FROM "ZOHO-0006 Invoice Lines"
GROUP BY "Customer Name"
If the data type is a string, you can use:如果数据类型是字符串,可以使用:
SELECT LEFT(datecol, 7) as yyyymm, ROUND(SUM("Price Ex"), 2) AS Sales
FROM "ZOHO-0006 Invoice Lines"
GROUP BY LEFT(datecol, 7);
If the value is stored as a date/time data type, use date functions, such as:如果值存储为日期/时间数据类型,请使用日期函数,例如:
SELECT YEAR(datecol), MONTH(datecol), ROUND(SUM("Price Ex"), 2) AS Sales
FROM "ZOHO-0006 Invoice Lines"
GROUP BY YEAR(datecol), MONTH(datecol);
To get the values in one column, you can use format()
:要获取一列中的值,可以使用format()
:
SELECT FORMAT(datecol, '%Y-%m') as yyyymm
Or extract()
:或extract()
:
SELECT EXTRACT(year_month from datecol) as yyyymm
If datatype of datecol is timestamp, you can try this:如果 datecol 的数据类型是时间戳,你可以试试这个:
SELECT
TO_CHAR(datecol,'YYYY-MM'),
ROUND(SUM("Price Ex"), 2) AS Sales
FROM "ZOHO-0006 Invoice Lines"
GROUP BY TO_CHAR(datecol,'YYYY-MM');
Or, if it is stored in text/ varchar2 format:或者,如果它以 text/varchar2 格式存储:
SELECT
TO_CHAR(TO_DATE(datecol,'YYYY-MM-DD HH:MI:SS'),'YYYY-MM'),
ROUND(SUM("Price Ex"), 2) AS Sales
FROM "ZOHO-0006 Invoice Lines"
GROUP BY TO_CHAR(datecol,'YYYY-MM');
Also, you no need to do 'distinct' explicitely.此外,您无需明确地“区分”。 'Group by' operation takes care of it. 'Group by' 操作负责处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.