Home > Database > Mysql Tutorial > How to Format Dates as 'Month-Year' When Grouping Data in SQL?

How to Format Dates as 'Month-Year' When Grouping Data in SQL?

Patricia Arquette
Release: 2025-01-04 14:44:39
Original
209 people have browsed it

How to Format Dates as

SQL Grouping by Month and Year: Enhanced Date Formatting

In this SQL query, you aim to modify the 'date' column to display the month and year in the "month-year" format, such as "9-2011." To achieve this, you can employ the following techniques:

Using CAST and CONCATENATION

The CAST function can convert your date components into VARCHAR strings. By concatenating the formatted month and year using the ' ' operator, you can obtain the desired format. Here's an example:

SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))
Copy after login

Using CAST with Leading Zeroes

If you prefer leading zeroes in your month formatting, you can use the following approach:

GROUP BY 
  CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2) 
Copy after login

This method ensures that single-digit months are padded with a leading zero.

The above is the detailed content of How to Format Dates as 'Month-Year' When Grouping Data in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template