Bạn có thể thử truy vấn bên dưới -
with X as (
select
l.*,
(select status_from from logs where logs.refno = l.refno and logs.logtime >= '2021-10-02' order by logs.logtime limit 1) logstat
from listings l
where l.added_date between '2021-10-01 00:00:00' and '2021-10-02 00:00:00' -- Start and end date range.
)
, Y as (select X.*, ifnull(X.logstat, X.status) stat20211001 from X)
SELECT
added_date,
COUNT(CASE WHEN status.text = 'Publish' THEN Y.id END) AS Publish,
COUNT(CASE WHEN status.text = 'Action' THEN Y.id END) AS Action,
COUNT(CASE WHEN status.text = 'Let' THEN Y.id END) AS Let,
COUNT(CASE WHEN status.text = 'Sold' THEN Y.id END) AS Sold,
COUNT(CASE WHEN status.text = 'Draft' THEN Y.id END) AS Draft
from status
join Y on Y.stat20211001 = status.code
group by added_date;