PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] How to (group by) date for every day in mysql

 February 21, 2022     laravel, mysql, php     No comments   

Issue

For my site admin panel, i need to show statistics for payments between two date

My payments table fields:

+--------------------+--------------+------+-----+-------------------+-----------------------------+
| Field              | Type         | Null | Key | Default           | Extra                       |
+--------------------+--------------+------+-----+-------------------+-----------------------------+
| id                 | int(11)      | NO   | PRI | NULL              | auto_increment              |
| price              | int(11)      | NO   |     | 0                 |                             |
| created            | timestamp    | NO   |     | CURRENT_TIMESTAMP |                             |
+--------------------+--------------+------+-----+-------------------+-----------------------------+

I need to get the payments data between tow days, day by day by php laravel to this structure

// date between 2021-12-01 and 2021-12-03

$data = [
    [
        'date' => '2021-12-01',
        'count' => 5 // number of payments records in 2021-12-01 in payments table
    ],
    [
        'date' => '2021-12-02',
        'count' => 0 // number of payments records in 2021-12-01 in payments table
    ],
    [
        'date' => '2021-12-03',
        'count' => 15 // number of payments records in 2021-12-01 in payments table
    ],
];

You should know maybe a day i haven't any payment and in database this day hasen't any records. but i need to show this day with count of 0

I don't know how do this


Solution

Using a recursive common table expression (in mysql 8 or mariadb 10.2+) to create your table of dates (here, reporting dates from 2021-01-01 to 2021-01-31):

with recursive dates as (
    select date('2021-01-01') date
    union all
    select dates.date + interval 1 day from dates where dates.date < '2021-01-31'
)
select dates.date, count(payments.id)
from dates
left join payments on date(payments.created)=dates.date
group by 1;


Answered By - ysth
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing