Search code examples
mysqlsqlsubquery

How to display the one column the data for 30 days and rest will display for 90 days with same query?


A few days ago I ask a question here and it's solved my issue using below query. I just added and t.date_of_created > DATE_SUB(NOW(), INTERVAL 90 DAY) to display the data only for 90 days and it's working.

Now my issue is, I have to show SUM(f_filestatus = 3) AS tcount3 only for 30 days and rest will display data for 90 days.

Any idea show to do this?

SELECT
  SUM(f_filestatus = 1) AS tcount1,
  SUM(f_filestatus = 2) AS tcount2,
  SUM(f_filestatus = 3) AS tcount3
FROM (
  SELECT t.f_bankid, t.f_filestatus
  FROM tbl_fileStatus t
  WHERE t.f_id = (SELECT f_id FROM tbl_fileStatus WHERE f_bankid = t.f_bankid and t.date_of_created > DATE_SUB(NOW(), INTERVAL 90 DAY) ORDER BY f_id DESC LIMIT 1)
) t

Solution

  • I would write your current query using window functions:

    SELECT SUM(f_filestatus = 1) AS tcount1,
           SUM(f_filestatus = 2) AS tcount2,
           SUM(f_filestatus = 3) AS tcount3
    FROM (SELECT fs.*,
                 ROW_NUMBER() OVER (PARTITION BY f_bank_id ORDER BY date_of_created DESC, f_id DESC) as seqnum
          FROM tbl_fileStatus fs
          WHERE fs.date_of_created > CURDATE() - INTERVAL 90 DAY
         ) fs
    WHERE seqnum = 1;
    

    But the answer to your question is to simply add a new condition:

    SELECT SUM(f_filestatus = 1) AS tcount1,
           SUM(f_filestatus = 2) AS tcount2,
           SUM(f_filestatus = 3 AND fs.date_of_created > CURDATE() - INTERVAL 30 DAY) AS tcount3
    FROM (SELECT fs.*,
                 ROW_NUMBER() OVER (PARTITION BY f_bank_id ORDER BY date_of_created DESC, f_id DESC) as seqnum
          FROM tbl_fileStatus fs
          WHERE fs.date_of_created > CURDATE() - INTERVAL 90 DAY
         ) fs
    WHERE seqnum = 1;
    

    EDIT:

    You can use the same idea in older versions:

    SELECT SUM(f_filestatus = 1) AS tcount1,
           SUM(f_filestatus = 2) AS tcount2,
           SUM(f_filestatus = 3 AND fs.date_of_created > CURDATE() - INTERVAL 30 DAY) AS tcount3
    FROM tbl_fileStatus fs
    WHERE fs.f_id = (SELECT fs2.f_id
                     FROM tbl_fileStatus fs2
                     WHERE fs2.bank_id = fs.bank_id AND
                           fs2.date_of_created > CURDATE() - INTERVAL 90 DAY
                     ORDER BY fs2.f_id DESC
                     LIMIT 1
                    )