- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a column of months from date and display sum of the corresponding column wherein you find duplicate dates?
For this can use DATE_FORMAT() in MySQL. Let us first create a table −
mysql> create table DemoTable -> ( -> PurchaseDate date, -> Amount int -> ); Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-10-12',500); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('2018-10-12',1000); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('2019-01-10',600); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('2018-10-12',600); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('2018-11-10',800); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+--------+ | PurchaseDate | Amount | +--------------+--------+ | 2019-10-12 | 500 | | 2018-10-12 | 1000 | | 2019-01-10 | 600 | | 2018-10-12 | 600 | | 2018-11-10 | 800 | +--------------+--------+ 5 rows in set (0.00 sec)
Here is the query to create a column of months from the date and display some of the corresponding columns wherein you find duplicate dates −
mysql> select sum(Amount) as Amount,date_format(PurchaseDate,'%b') AS Month from DemoTable -> group by date_format(PurchaseDate,'%Y-%m');
This will produce the following output −
+--------+-------+ | Amount | Month | +--------+-------+ | 500 | Oct | | 1600 | Oct | | 600 | Jan | | 800 | Nov | +--------+-------+ 4 rows in set (0.00 sec)
Advertisements